﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zocono.Infrastructure.Common;
using Zocono.WCS.Domain.DomainRepository;
using Zocono.WCS.Domain.EntityInfo;
using Zocono.WCS.Infrastructure.ApllicationDto.Enums;
using Zocono.WCS.Domain.PlcBytesObject;
using Zocono.WCS.Infrastructure.ApllicationDto.WCSTaskDto;
using Zocono.WCS.WMSApiDomain.WebApi;
using Zocono.WCS.Domain.LogDomain;
using AutoMapper;
using Zocono.WCS.Infrastructure.ApllicationDto.WmsModel;
using Zocono.WCS.Domain.WcsGetWmsJobDomain;

namespace Zocono.WCS.Domain.ScGetWMSTaskDomain
{
    public class ScGetWMSTaskService : IScGetWMSTaskService
    {
        private readonly IWcsGetWmsJobService _wcsGetWmsJobService;
        private readonly IRedisHelper _iRedisHelper;
        private readonly ILogUtil _LogUtil;
        private readonly ISnowflake _Sonoflake;
        private readonly IWorkTaskInfoRepository _WorkTaskInfoRepository;
        private readonly IRunLogInfoService _IRunLogInfoService;
        private readonly IMapper _mapper;


        public ScGetWMSTaskService(IWcsGetWmsJobService wcsGetWmsJobService, IRedisHelper iRedisHelper, ILogUtil logUtil, ISnowflake snowflake, IWorkTaskInfoRepository workTaskInfoRepository, IRunLogInfoService runLogInfoService, IMapper mapper)
        {
            _wcsGetWmsJobService = wcsGetWmsJobService;
            _iRedisHelper = iRedisHelper;
            _LogUtil = logUtil;
            _Sonoflake = snowflake;
            _WorkTaskInfoRepository = workTaskInfoRepository;
            _IRunLogInfoService = runLogInfoService;
            _mapper = mapper;
        }

        /// <summary>
        /// 获取WMS作业；
        /// </summary>
        /// <param name="scCode"></param>
        /// <param name="model">1入巷道 2 出巷道</param>
        /// <returns></returns>
        public async Task<List<WCSWorkTaskInfoDto>> ScGetWorkTaskInfoAsync(string scCode, int model)
        {
            List<WCSWorkTaskInfoDto> wCSWorkTasks = new List<WCSWorkTaskInfoDto>();
            if (model == 1)
            {
                var exp = Expressionable.Create<WorkTaskInfo, RouteDetailInfo>();
                exp.AndIF(true, (wti, ri) => ri.ToEquipment == scCode);
                exp.AndIF(true, (wti, ri) => wti.TaskState == 0 || wti.TaskState == EnumTaskState.Executing);
                exp.AndIF(true, (wti, ri) => wti.CurrentDetailTaskState == 0);
                exp.AndIF(true, (wti, ri) => wti.CurrentDispatchType == EnumDispatchType.SC_UP || wti.CurrentDispatchType == EnumDispatchType.SC_MOVE);

                wCSWorkTasks = await _WorkTaskInfoRepository.AsSugarClient()
                .Queryable<WorkTaskInfo, RouteDetailInfo>((wti, ri) => new JoinQueryInfos(JoinType.Inner, wti.CurrentRounteDetailID == ri.ID))
                .Where(exp.ToExpression())
                .Select((wti, ri) => new WCSWorkTaskInfoDto()
                {
                    ID = wti.ID,
                    RouteID = wti.RouteID,
                    Priority = wti.Priority,
                    PalletCode = wti.PalletCode,
                    TaskCode = wti.TaskCode,
                    TaskProcessState = wti.TaskProcessState,
                    TaskState = wti.TaskState,
                    TaskType = wti.TaskType,
                    SaveTime = wti.SaveTime,
                    UpdateTime = wti.UpdateTime,
                    WmsTaskCode = wti.WmsTaskCode,
                    DependWmsTaskCode = wti.DependWmsTaskCode,
                    WmsFromStation = wti.WmsFromStation,
                    WmsFromPosition = wti.WmsFromPosition.ToString(),
                    WmsToStation = wti.WmsToStation,
                    WmsToPosition = wti.WmsToPosition,
                    CurrentRounteDetailID = wti.CurrentRounteDetailID,
                    CurrentDetailTaskState = wti.CurrentDetailTaskState,
                    CurrentDispatchType = wti.CurrentDispatchType,
                    CurrentFromEquipment = wti.CurrentFromEquipment,
                    CurrentFromCargo = wti.CurrentFromCargo,
                    CurrentToEquipment = wti.CurrentToEquipment,
                    CurrentToCargo = wti.CurrentToCargo,
                    CurrentCreateTime = wti.CurrentCreateTime,
                    CurrentUpdateTime = wti.CurrentUpdateTime
                })
                .ToListAsync();
            }
            else if (model == 2)
            {
                var exp = Expressionable.Create<WorkTaskInfo, RouteDetailInfo>();
                exp.AndIF(true, (wti, ri) => ri.FromEquipment == scCode);
                exp.AndIF(true, (wti, ri) => wti.TaskState == 0 || wti.TaskState == EnumTaskState.Executing);
                exp.AndIF(true, (wti, ri) => wti.CurrentDetailTaskState == 0);

                exp.AndIF(true, (wti, ri) => wti.CurrentDispatchType == EnumDispatchType.SC_DOWN || wti.CurrentDispatchType == EnumDispatchType.SC_CROSS);

                wCSWorkTasks = await _WorkTaskInfoRepository.AsSugarClient()
                .Queryable<WorkTaskInfo, RouteDetailInfo>((wti, ri) => new JoinQueryInfos(JoinType.Inner, wti.CurrentRounteDetailID == ri.ID))
                .Where(exp.ToExpression())
                .Select((wti, ri) => new WCSWorkTaskInfoDto()
                {
                    ID = wti.ID,
                    RouteID = wti.RouteID,
                    Priority = wti.Priority,
                    PalletCode = wti.PalletCode,
                    TaskCode = wti.TaskCode,
                    TaskProcessState = wti.TaskProcessState,
                    TaskState = wti.TaskState,
                    TaskType = wti.TaskType,
                    SaveTime = wti.SaveTime,
                    UpdateTime = wti.UpdateTime,
                    WmsTaskCode = wti.WmsTaskCode,
                    DependWmsTaskCode = wti.DependWmsTaskCode,
                    WmsFromStation = wti.WmsFromStation,
                    WmsFromPosition = wti.WmsFromPosition.ToString(),
                    WmsToStation = wti.WmsToStation,
                    WmsToPosition = wti.WmsToPosition,
                    CurrentRounteDetailID = wti.CurrentRounteDetailID,
                    CurrentDetailTaskState = wti.CurrentDetailTaskState,
                    CurrentDispatchType = wti.CurrentDispatchType,
                    CurrentFromEquipment = wti.CurrentFromEquipment,
                    CurrentFromCargo = wti.CurrentFromCargo,
                    CurrentToEquipment = wti.CurrentToEquipment,
                    CurrentToCargo = wti.CurrentToCargo,
                    CurrentCreateTime = wti.CurrentCreateTime,
                    CurrentUpdateTime = wti.CurrentUpdateTime
                })
                .ToListAsync();
            }
            return wCSWorkTasks;
        }

        /// <summary>
        /// 从缓存中获取堆垛机任务
        /// </summary>
        /// <param name="scCode"></param>
        /// <param name="planarStateBOs"></param>
        /// <returns></returns>
        public async Task<WCSWorkTaskInfoDto> ScGetCurrentTaskInfoAsync(string scCode, List<PlanarStateBO> planarStateBOs)
        {
            RunLogInfo runLogInfo = new RunLogInfo();
            runLogInfo.ContainerBarcode = "不获取";
            runLogInfo.EquipmentCode = scCode;
            runLogInfo.RunType = "获取堆垛机任务";

            //先找出符合条件的路径详情
            var routeDetailInfos = _iRedisHelper.GetStringKey<List<RouteDetailInfo>>("RouteDetailInfo");
            //从巷道出库路径详情
            var outScRouteDetails = routeDetailInfos.Where(it => it.FromEquipment == scCode).Select(it => it.ID).ToList();
            //入库巷道路径详情
            var inScRouteDetails = routeDetailInfos.Where(it => it.ToEquipment == scCode).Select(it => it.ID).ToList();

            //首先判断是否有优先级高的任务，堆垛机优先执行
            var initTsks = _wcsGetWmsJobService.GetScWorkTaskInfo((WCSWorkTaskInfoDto wti) => wti.Priority > 1 && outScRouteDetails.Contains(wti.CurrentRounteDetailID));
            if (initTsks.Any())
            {
                //按优先级和时间顺序排序
                initTsks = initTsks
                            .OrderByDescending(wti => wti.Priority)
                            .ThenBy(wti => wti.CurrentUpdateTime)
                            .ToList();
                foreach (var tsk in initTsks)
                {
                    //出库任务需要校验出库台是否空闲
                    if (tsk.CurrentDispatchType == EnumDispatchType.SC_DOWN)
                    {
                        PlanarStateBO dostation = planarStateBOs.Find(it => it.EquipmentCode.ToString() == tsk.CurrentToEquipment);
                        if (dostation == null)
                        {
                            runLogInfo.RunLog = $"任务出库台【{tsk.CurrentToEquipment}】 没有配置交接台信息";
                            await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                            continue;
                        }

                        if (dostation.PalletBarcode.Trim().Length == 0 && dostation.Reserve == 0 && dostation.ActionType == 3)
                        {
                            return tsk;
                        }
                        else
                        {
                            runLogInfo.RunLog = $"交接台【{tsk.CurrentToEquipment}】设备状态占位，托盘码【{dostation.PalletBarcode.Trim()}】,占位标识【{dostation.Reserve}】，握手标识【{dostation.ActionType}】";
                            await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                            continue;

                        }
                    }
                    else //其他任务优先级高直接执行
                    {
                        return tsk;
                    }
                }
            }
            //以上没有优先级任务则按照时间顺序和堆垛机作业模式拿取相应任务
            //获取堆垛机作业模式
            var scmodel = await ScGetScWorkModelInfoAsync(scCode);
            if (scmodel == null)
                return null;
            int currentMode = scmodel.WorkModel;
            //入库模式
            if (currentMode == 3 || currentMode == 1 || currentMode == 7 || currentMode == 9)
            {
                var ruKuTask = await ruKuMode(planarStateBOs, runLogInfo, inScRouteDetails, scmodel, currentMode);
                if (ruKuTask != null)
                {
                    return ruKuTask;
                }
                currentMode = 2;
            }

            //出库模式
            if (currentMode == 4 || currentMode == 2 || currentMode == 10)
            {
                var chuKuTask = await chuKuMode(planarStateBOs, runLogInfo, outScRouteDetails, scmodel, currentMode);
                if (chuKuTask != null)
                {
                    return chuKuTask;
                }
                currentMode = 5;
            }

            //移库模式
            if (currentMode == 6 || currentMode == 5 || currentMode == 8)
            {
                //除了只移 其他都需要轮询交替
                if (currentMode == 5 || currentMode == 8)
                {
                    switch (currentMode)
                    {
                        case 5:
                            scmodel.WorkModel = 1; break;
                        case 8:
                            scmodel.WorkModel = 7; break;
                        default:
                            break;
                    }
                    scmodel.UpdateTime = DateTime.Now;
                    await ScUpdateScWorkModelInfoAsync(scmodel);
                }

                //从缓存中拿符合条件的任务
                var initTsksOut = _wcsGetWmsJobService.GetScWorkTaskInfo((WCSWorkTaskInfoDto wti) => wti.CurrentDispatchType == EnumDispatchType.SC_MOVE && outScRouteDetails.Contains(wti.CurrentRounteDetailID));
                if (!initTsksOut.Any())
                {
                    return null;
                }
                return initTsksOut.First();
            }

            return null;
        }

        /// <summary>
        /// 出库模式
        /// </summary>
        /// <param name="planarStateBOs"></param>
        /// <param name="runLogInfo"></param>
        /// <param name="outScRouteDetails"></param>
        /// <param name="scmodel"></param>
        /// <param name="currentMode"></param>
        /// <returns></returns>
        private async Task<WCSWorkTaskInfoDto> chuKuMode(List<PlanarStateBO> planarStateBOs, RunLogInfo runLogInfo, List<long> outScRouteDetails, ScWorkModelInfo scmodel, int currentMode)
        {
            //除了只出模式 其他需要轮询交替
            if (currentMode == 2 || currentMode == 10)
            {
                switch (currentMode)
                {
                    case 2:
                        scmodel.WorkModel = 5; break;
                    case 10:
                        scmodel.WorkModel = 9; break;
                    default:
                        break;
                }
                scmodel.UpdateTime = DateTime.Now;
                await ScUpdateScWorkModelInfoAsync(scmodel);
            }

            //从缓存中拿符合条件的任务
            var initTsksOut = _wcsGetWmsJobService.GetScWorkTaskInfo((WCSWorkTaskInfoDto wti) => wti.CurrentDispatchType == EnumDispatchType.SC_DOWN && outScRouteDetails.Contains(wti.CurrentRounteDetailID));
            if (!initTsksOut.Any())
            {
                return null;
            }
            //按优先级和时间顺序排序
            initTsksOut = initTsksOut
                        .OrderByDescending(wti => wti.Priority)
                        .ThenBy(wti => wti.CurrentUpdateTime)
                        .ToList();
            foreach (var tsk in initTsksOut)
            {
                PlanarStateBO dostation = planarStateBOs.Find(it => it.EquipmentCode == tsk.CurrentToEquipment);
                if (dostation == null)
                {
                    runLogInfo.RunLog = $"任务出库台【{tsk.CurrentToEquipment}】 没有配置交接台信息";
                    await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                    continue;
                }

                if (dostation.PalletBarcode.Trim().Length == 0 && dostation.Reserve == 0 && dostation.ActionType == 3)
                {
                    return tsk;
                }
                else
                {
                    runLogInfo.RunLog = $"交接台【{tsk.CurrentToEquipment}】设备状态占位，托盘码【{dostation.PalletBarcode.Trim()}】,占位标识【{dostation.Reserve}】，握手标识【{dostation.ActionType}】";
                    await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                    continue;
                }
            }
            return null;
        }

        /// <summary>
        /// 入库模式
        /// </summary>
        /// <param name="planarStateBOs"></param>
        /// <param name="runLogInfo"></param>
        /// <param name="inScRouteDetails"></param>
        /// <param name="scmodel"></param>
        /// <param name="currentMode"></param>
        /// <returns></returns>
        private async Task<WCSWorkTaskInfoDto> ruKuMode(List<PlanarStateBO> planarStateBOs, RunLogInfo runLogInfo, List<long> inScRouteDetails, ScWorkModelInfo scmodel, int currentMode)
        {
            //除了 只入库 模式以外 其他模式都是轮询交替
            if (currentMode == 1 || currentMode == 7 || currentMode == 9)
            {
                switch (currentMode)
                {
                    case 1:
                        scmodel.WorkModel = 2; break;
                    case 7:
                        scmodel.WorkModel = 8; break;
                    case 9:
                        scmodel.WorkModel = 10; break;
                    default:
                        break;
                }
                scmodel.UpdateTime = DateTime.Now;
                await ScUpdateScWorkModelInfoAsync(scmodel);
            }
            //从缓存中拿符合条件的任务
            var initTsksIns = _wcsGetWmsJobService.GetScWorkTaskInfo((WCSWorkTaskInfoDto wti) => wti.CurrentDispatchType == EnumDispatchType.SC_UP && inScRouteDetails.Contains(wti.CurrentRounteDetailID));
            if (!initTsksIns.Any())
            {
                return null;
            }
            //按优先级和时间顺序排序
            initTsksIns = initTsksIns
                        .OrderByDescending(wti => wti.Priority)
                        .ThenBy(wti => wti.CurrentUpdateTime)
                        .ToList();
            //拿到任务跟入库台信息对比一下
            var firstWorkTask = initTsksIns.First();
            //拿到当前任务入库台的设备号报文信息
            PlanarStateBO puStationBo = planarStateBOs.Find(it => it.EquipmentCode.ToString() == firstWorkTask.CurrentFromEquipment);
            if (puStationBo == null)
            {
                runLogInfo.RunLog = $"入库台【{firstWorkTask.CurrentFromEquipment}】没有配置交接台信息";
                await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                //如果没有配置入库台占位报文，则先返回第一条任务 TODO 考虑是否直接返回null
                return firstWorkTask;
            }
            //判断当前任务是否是入库台的任务
            if (puStationBo.TaskCode == firstWorkTask.TaskCode && puStationBo.PalletBarcode.Trim() == firstWorkTask.PalletCode)
            {
                return firstWorkTask;
            }
            else
            {
                //拿到入库台的任务和托盘码
                var tempTask = initTsksIns.Where(it => it.PalletCode == puStationBo.PalletBarcode.ToString() && it.TaskCode == puStationBo.TaskCode).FirstOrDefault();
                if (tempTask != null)
                {
                    return tempTask;
                }
                else
                {
                    runLogInfo.RunLog = $"入库台【{firstWorkTask.CurrentFromEquipment}】托盘【{puStationBo.PalletBarcode}】任务【{puStationBo.TaskCode}】异常，请检查入库台信息和任务！";
                    await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                    return null;
                }
            }
        }



        /// <summary>
        /// 从WorkTaskInfo表中获取任务，来源于
        /// </summary>
        /// <param name="scCode"></param>
        /// <param name="planarStateBOs"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<WCSWorkTaskInfoDto> ScGetFirstWorkTaskInfoAsync(string scCode, List<PlanarStateBO> planarStateBOs)
        {
            if (_LogUtil.LogOpen == "1")
            {
                _LogUtil.Debug($"获取{scCode}准备获取任务");
            }
            RunLogInfo runLogInfo = new RunLogInfo();
            runLogInfo.ContainerBarcode = "不获取";
            runLogInfo.EquipmentCode = scCode;
            runLogInfo.RunType = "获取堆垛机任务";
            var scmodel = await ScGetScWorkModelInfoAsync(scCode);
            if (scmodel == null)
                return null;
            int currentMode = scmodel.WorkModel;
            if (_LogUtil.LogOpen == "1")
            {
                _LogUtil.Debug($"获取{scCode}准备获取任务|堆垛机模式{currentMode}");
            }

            ////先找出符合条件的路径详情 TODO20240729 后面需修改从内存读取数据，暂时注释
            //var routeDetailInfos = _iRedisHelper.GetStringKey<List<RouteDetailInfo>>("RouteDetailInfo");
            ////从巷道出库路径详情
            //var outScRouteDetails = routeDetailInfos.Find(it=>it.FromEquipment == scCode);
            ////入库巷道路径详情
            //var inScRouteDetails = routeDetailInfos.Find(it => it.ToEquipment == scCode);

            //查询是否有优先级高的任务
            {
                var exp = Expressionable.Create<WorkTaskInfo, RouteDetailInfo>();
                exp.AndIF(true, (wti, ri) => ri.FromEquipment == scCode);
                exp.AndIF(true, (wti, ri) => wti.TaskState == EnumTaskState.Initial || wti.TaskState == EnumTaskState.Executing);
                exp.AndIF(true, (wti, ri) => wti.CurrentDetailTaskState == EnumDetailTaskState.Init);
                exp.AndIF(true, (wti, ri) => wti.Priority > 1);

                var wmstasks = await _WorkTaskInfoRepository.AsSugarClient()
                .Queryable<WorkTaskInfo, RouteDetailInfo>((wti, ri) => new JoinQueryInfos(JoinType.Inner, wti.CurrentRounteDetailID == ri.ID))
                .Where(exp.ToExpression())
                .OrderBy((wti, ri) => wti.Priority, OrderByType.Desc)
                .OrderBy((wti, ri) => wti.CurrentUpdateTime, OrderByType.Asc)
                .Select((wti, ri) => new WCSWorkTaskInfoDto()
                {
                    ID = wti.ID,
                    RouteID = wti.RouteID,
                    Priority = wti.Priority,
                    PalletCode = wti.PalletCode,
                    TaskCode = wti.TaskCode,
                    TaskProcessState = wti.TaskProcessState,
                    TaskState = wti.TaskState,
                    TaskType = wti.TaskType,
                    SaveTime = wti.SaveTime,
                    UpdateTime = wti.UpdateTime,
                    WmsTaskCode = wti.WmsTaskCode,
                    DependWmsTaskCode = wti.DependWmsTaskCode,
                    WmsFromStation = wti.WmsFromStation,
                    WmsFromPosition = wti.WmsFromPosition.ToString(),
                    WmsToStation = wti.WmsToStation,
                    WmsToPosition = wti.WmsToPosition,
                    CurrentRounteDetailID = wti.CurrentRounteDetailID,
                    CurrentDetailTaskState = wti.CurrentDetailTaskState,
                    CurrentDispatchType = wti.CurrentDispatchType,
                    CurrentFromEquipment = wti.CurrentFromEquipment,
                    CurrentFromCargo = wti.CurrentFromCargo,
                    CurrentToEquipment = wti.CurrentToEquipment,
                    CurrentToCargo = wti.CurrentToCargo,
                    CurrentCreateTime = wti.CurrentCreateTime,
                    CurrentUpdateTime = wti.CurrentUpdateTime
                })
                .ToListAsync();

                if (wmstasks.Count > 0)
                {
                    //return wmstasks.First();
                    foreach (var temp in wmstasks)
                    {
                        try
                        {
                            //置顶任务
                            if (temp.Priority == 9999)
                            {
                                if (temp.CurrentDispatchType == EnumDispatchType.SC_DOWN)
                                {
                                    PlanarStateBO dostation = planarStateBOs.Find(it => it.EquipmentCode.ToString() == temp.CurrentToEquipment);
                                    if (dostation == null)
                                    {
                                        runLogInfo.RunLog = $"{temp.CurrentToEquipment} 没有配置交接台信息";
                                        await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                                        continue;
                                    }

                                    if (dostation.PalletBarcode.Trim().Length == 0 && dostation.Reserve == 0 && dostation.ActionType == 3)
                                    {
                                        return temp;
                                    }
                                    else
                                    {
                                        runLogInfo.RunLog = $"交接台{temp.CurrentToEquipment}设备状态占位";
                                        await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                                        continue;

                                    }

                                }
                                else
                                {
                                    return temp;
                                }
                            }
                            //判断其他优先级任务
                            if (temp.Priority > 1)
                            {
                                if (temp.CurrentDispatchType == EnumDispatchType.SC_DOWN)
                                {
                                    PlanarStateBO dostation = planarStateBOs.Find(it => it.EquipmentCode.ToString() == temp.CurrentToEquipment);
                                    if (dostation == null)
                                    {
                                        runLogInfo.RunLog = $"{temp.CurrentToEquipment} 没有配置交接台信息";
                                        await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                                        continue;
                                    }

                                    if (dostation.PalletBarcode.Trim().Length == 0 && dostation.Reserve == 0 && dostation.ActionType == 3)
                                    {
                                        return temp;
                                    }
                                    else
                                    {
                                        runLogInfo.RunLog = $"交接台{temp.CurrentToEquipment}设备状态占位";
                                        await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                                        continue;

                                    }

                                }
                                else
                                {
                                    return temp;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            runLogInfo.RunLog = $"SC设备{scCode} 配置的{ex.Message}";
                            await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                        }
                    }
                }
            }

            //入库
            if (currentMode == 3 || currentMode == 1 || currentMode == 7 || currentMode == 9)
            {
                #region 入库
                //入库
                if (currentMode == 3 || currentMode == 1 || currentMode == 7 || currentMode == 9)
                {
                    if (currentMode == 1 || currentMode == 7 || currentMode == 9)
                    {
                        switch (currentMode)
                        {
                            case 1:
                                scmodel.WorkModel = 2; break;
                            case 7:
                                scmodel.WorkModel = 8; break;
                            case 9:
                                scmodel.WorkModel = 10; break;
                            default:
                                break;
                        }
                        scmodel.UpdateTime = DateTime.Now;
                        await ScUpdateScWorkModelInfoAsync(scmodel);
                    }
                    var exp = Expressionable.Create<WorkTaskInfo, RouteDetailInfo>();
                    exp.AndIF(true, (wti, ri) => wti.CurrentDispatchType == EnumDispatchType.SC_UP);
                    exp.AndIF(true, (wti, ri) => ri.ToEquipment == scCode);
                    exp.AndIF(true, (wti, ri) => wti.TaskState == EnumTaskState.Executing || wti.TaskState == EnumTaskState.Initial);
                    exp.AndIF(true, (wti, ri) => wti.CurrentDetailTaskState == EnumDetailTaskState.Init);

                    var wmstasks = await _WorkTaskInfoRepository.AsSugarClient()
                    .Queryable<WorkTaskInfo, RouteDetailInfo>((wti, ri) => new JoinQueryInfos(JoinType.Inner, wti.CurrentRounteDetailID == ri.ID))
                    .Where(exp.ToExpression()).OrderBy((wti, ri) => wti.Priority, OrderByType.Desc).OrderBy((wti, ri) => wti.CurrentUpdateTime, OrderByType.Asc)
                    .Select((wti, ri) => new WCSWorkTaskInfoDto()
                    {
                        ID = wti.ID,
                        RouteID = wti.RouteID,
                        Priority = wti.Priority,
                        PalletCode = wti.PalletCode,
                        TaskCode = wti.TaskCode,
                        TaskProcessState = wti.TaskProcessState,
                        TaskState = wti.TaskState,
                        TaskType = wti.TaskType,
                        SaveTime = wti.SaveTime,
                        UpdateTime = wti.UpdateTime,
                        WmsTaskCode = wti.WmsTaskCode,
                        DependWmsTaskCode = wti.DependWmsTaskCode,
                        WmsFromStation = wti.WmsFromStation,
                        WmsFromPosition = wti.WmsFromPosition.ToString(),
                        WmsToStation = wti.WmsToStation,
                        WmsToPosition = wti.WmsToPosition,
                        CurrentRounteDetailID = wti.CurrentRounteDetailID,
                        CurrentDetailTaskState = wti.CurrentDetailTaskState,
                        CurrentDispatchType = wti.CurrentDispatchType,
                        CurrentFromEquipment = wti.CurrentFromEquipment,
                        CurrentFromCargo = wti.CurrentFromCargo,
                        CurrentToEquipment = wti.CurrentToEquipment,
                        CurrentToCargo = wti.CurrentToCargo,
                        CurrentCreateTime = wti.CurrentCreateTime,
                        CurrentUpdateTime = wti.CurrentUpdateTime
                    })
                    .ToListAsync();

                    if (_LogUtil.LogOpen == "1")
                    {
                        _LogUtil.Debug($"1.获取{scCode}入库任务");
                    }

                    if (wmstasks.Count > 0)
                    {
                        //拿到任务跟入库台信息对比一下
                        var firstWorkTask = wmstasks.First();
                        //拿到当前任务入库台的设备号报文信息
                        PlanarStateBO puStationBo = planarStateBOs.Find(it => it.EquipmentCode.ToString() == firstWorkTask.CurrentFromEquipment);
                        if (puStationBo == null)
                        {
                            runLogInfo.RunLog = $"入库台 {firstWorkTask.CurrentFromEquipment} 没有配置交接台信息";
                            await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                            //如果没有配置入库台占位报文，则先返回第一条任务
                            return firstWorkTask;
                        }
                        //判断当前任务是否是入库台的任务
                        if (puStationBo.TaskCode == firstWorkTask.TaskCode && puStationBo.PalletBarcode.Trim() == firstWorkTask.PalletCode)
                        {
                            return firstWorkTask;
                        }
                        else
                        {
                            //拿到入库台的任务和托盘码
                            var tempTask = wmstasks.Find(it => it.PalletCode == puStationBo.PalletBarcode.ToString() && it.TaskCode == puStationBo.TaskCode);
                            if (tempTask != null)
                            {
                                return tempTask;
                            }
                            else
                            {
                                runLogInfo.RunLog = $"入库台 {firstWorkTask.CurrentFromEquipment} 托盘任务异常，请检查入库台信息和任务！";
                                await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                            }
                        }
                    }
                    else
                    {
                        switch (currentMode)
                        {
                            case 1:
                                currentMode = 2; break;
                            case 7:
                                currentMode = 8; break;
                            case 9:
                                currentMode = 10; break;

                            default:
                                break;
                        }


                    }
                }
                //出库
                if (currentMode == 4 || currentMode == 2 || currentMode == 10)
                {
                    if (currentMode == 2 || currentMode == 10)
                    {
                        switch (currentMode)
                        {
                            case 2:
                                scmodel.WorkModel = 5; break;
                            case 10:
                                scmodel.WorkModel = 9; break;
                            default:
                                break;
                        }

                        scmodel.UpdateTime = DateTime.Now;
                        await ScUpdateScWorkModelInfoAsync(scmodel);
                    }

                    var exp = Expressionable.Create<WorkTaskInfo, RouteDetailInfo>();
                    exp.AndIF(true, (wti, ri) => ri.FromEquipment == scCode);
                    exp.AndIF(true, (wti, ri) => wti.TaskState == EnumTaskState.Initial || wti.TaskState == EnumTaskState.Executing);
                    exp.AndIF(true, (wti, ri) => wti.CurrentDetailTaskState == EnumDetailTaskState.Init);
                    exp.AndIF(true, (wti, ri) => wti.CurrentDispatchType == EnumDispatchType.SC_DOWN || wti.CurrentDispatchType == EnumDispatchType.SC_CROSS);

                    var wmstasks = await _WorkTaskInfoRepository.AsSugarClient()
                    .Queryable<WorkTaskInfo, RouteDetailInfo>((wti, ri) => new JoinQueryInfos(JoinType.Inner, wti.CurrentRounteDetailID == ri.ID))
                    .Where(exp.ToExpression()).OrderBy((wti, ri) => wti.Priority, OrderByType.Desc).OrderBy((wti, ri) => wti.SaveTime, OrderByType.Asc)
                    .Select((wti, ri) => new WCSWorkTaskInfoDto()
                    {
                        ID = wti.ID,
                        RouteID = wti.RouteID,
                        Priority = wti.Priority,
                        PalletCode = wti.PalletCode,
                        TaskCode = wti.TaskCode,
                        TaskProcessState = wti.TaskProcessState,
                        TaskState = wti.TaskState,
                        TaskType = wti.TaskType,
                        SaveTime = wti.SaveTime,
                        UpdateTime = wti.UpdateTime,
                        WmsTaskCode = wti.WmsTaskCode,
                        DependWmsTaskCode = wti.DependWmsTaskCode,
                        WmsFromStation = wti.WmsFromStation,
                        WmsFromPosition = wti.WmsFromPosition.ToString(),
                        WmsToStation = wti.WmsToStation,
                        WmsToPosition = wti.WmsToPosition,
                        CurrentRounteDetailID = wti.CurrentRounteDetailID,
                        CurrentDetailTaskState = wti.CurrentDetailTaskState,
                        CurrentDispatchType = wti.CurrentDispatchType,
                        CurrentFromEquipment = wti.CurrentFromEquipment,
                        CurrentFromCargo = wti.CurrentFromCargo,
                        CurrentToEquipment = wti.CurrentToEquipment,
                        CurrentToCargo = wti.CurrentToCargo,
                        CurrentCreateTime = wti.CurrentCreateTime,
                        CurrentUpdateTime = wti.CurrentUpdateTime
                    })
                    .ToListAsync();

                    if (_LogUtil.LogOpen == "1")
                    {
                        _LogUtil.Debug($"1.获取{scCode}出库任务");
                    }
                    if (wmstasks.Count > 0)
                    {
                        #region 重复任务
                        var tasksame = wmstasks.GroupBy(x => x.WmsTaskCode)
                                                .Where(g => g.Count() > 1)
                                                .Select(y => y)
                                                .ToList();
                        //删除重复的任务
                        if (tasksame.Count != 0 && tasksame != null)
                        {
                            foreach (var tasks in tasksame)
                            {
                                var task = tasks.AsEnumerable().ToList();
                                task.Remove(task.First());
                                foreach (var item in task)
                                {
                                    wmstasks.Remove(item);
                                }

                                var tts = _mapper.Map<List<WCSWorkTaskInfoDto>, List<WorkTaskInfo>>(task);
                                await _WorkTaskInfoRepository.AsSugarClient().Deleteable(tts).ExecuteCommandAsync();
                            }

                        }
                        #endregion

                        foreach (var temp in wmstasks)
                        {
                            try
                            {
                                PlanarStateBO dostation = planarStateBOs.Find(it => it.EquipmentCode == temp.CurrentToEquipment);
                                if (dostation == null)
                                {
                                    runLogInfo.RunLog = $"{temp.CurrentToEquipment} 没有配置交接台信息";
                                    await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                                    continue;
                                }

                                if (dostation.PalletBarcode.Trim().Length == 0 && dostation.Reserve == 0 && dostation.ActionType == 3)
                                {
                                    return temp;
                                }
                                else
                                {
                                    runLogInfo.RunLog = $"交接台{temp.CurrentToEquipment}设备状态占位";
                                    await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                                    continue;
                                }
                            }
                            catch (Exception ex)
                            {
                                runLogInfo.RunLog = $"SC设备{scCode} 配置的{ex.Message}";
                                await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                            }
                        }
                    }
                    else
                    {
                        switch (currentMode)
                        {
                            case 2:
                                currentMode = 5; break;
                            case 10:
                                currentMode = 9; break;

                            default:
                                break;
                        }

                    }
                }
                //移库
                if (currentMode == 6 || currentMode == 5 || currentMode == 8)
                {
                    if (currentMode == 5 || currentMode == 8)
                    {
                        switch (currentMode)
                        {
                            case 5:
                                scmodel.WorkModel = 1; break;
                            case 8:
                                scmodel.WorkModel = 7; break;
                            default:
                                break;
                        }
                        scmodel.UpdateTime = DateTime.Now;
                        await ScUpdateScWorkModelInfoAsync(scmodel);
                    }

                    var exp = Expressionable.Create<WorkTaskInfo, RouteDetailInfo>();
                    exp.AndIF(true, (wti, ri) => ri.ToEquipment == scCode);//哪台堆垛机
                    exp.AndIF(true, (wti, ri) => wti.TaskState == EnumTaskState.Executing || wti.TaskState == EnumTaskState.Initial);
                    exp.AndIF(true, (wti, ri) => wti.CurrentDetailTaskState == EnumDetailTaskState.Init);
                    exp.AndIF(true, (wti, ri) => wti.CurrentDispatchType == EnumDispatchType.SC_MOVE);

                    var wmstasks = await _WorkTaskInfoRepository.AsSugarClient()
                    .Queryable<WorkTaskInfo, RouteDetailInfo>((wti, ri) => new JoinQueryInfos(JoinType.Inner, wti.CurrentRounteDetailID == ri.ID))
                    .Where(exp.ToExpression())
                    .OrderBy(wti => wti.Priority, OrderByType.Desc)
                    .OrderBy(wti => wti.SaveTime, OrderByType.Asc)
                    .Select((wti, ri) => new WCSWorkTaskInfoDto()
                    {
                        ID = wti.ID,
                        RouteID = wti.RouteID,
                        Priority = wti.Priority,
                        PalletCode = wti.PalletCode,
                        TaskCode = wti.TaskCode,
                        TaskProcessState = wti.TaskProcessState,
                        TaskState = wti.TaskState,
                        TaskType = wti.TaskType,
                        SaveTime = wti.SaveTime,
                        UpdateTime = wti.UpdateTime,
                        WmsTaskCode = wti.WmsTaskCode,
                        DependWmsTaskCode = wti.DependWmsTaskCode,
                        WmsFromStation = wti.WmsFromStation,
                        WmsFromPosition = wti.WmsFromPosition.ToString(),
                        WmsToStation = wti.WmsToStation,
                        WmsToPosition = wti.WmsToPosition,
                        CurrentRounteDetailID = wti.CurrentRounteDetailID,
                        CurrentDetailTaskState = wti.CurrentDetailTaskState,
                        CurrentDispatchType = wti.CurrentDispatchType,
                        CurrentFromEquipment = wti.CurrentFromEquipment,
                        CurrentFromCargo = wti.CurrentFromCargo,
                        CurrentToEquipment = wti.CurrentToEquipment,
                        CurrentToCargo = wti.CurrentToCargo,
                        CurrentCreateTime = wti.CurrentCreateTime,
                        CurrentUpdateTime = wti.CurrentUpdateTime
                    })
                    .ToListAsync();

                    if (_LogUtil.LogOpen == "1")
                    {
                        _LogUtil.Debug($"1.获取{scCode}移库任务");
                    }

                    if (wmstasks.Count > 0)
                    {
                        return wmstasks.First();

                    }
                    else
                    {
                        if (currentMode == 5 || currentMode == 8)
                        {
                            switch (currentMode)
                            {
                                case 5:
                                    currentMode = 1; break;
                                case 8:
                                    currentMode = 7; break;
                                default:
                                    break;
                            }
                        }
                    }

                }
                #endregion

                if (_LogUtil.LogOpen == "1")
                {
                    _LogUtil.Debug($"1.获取{scCode}入库完成，不存在任务");
                }
                return null;
            }

            if (currentMode == 4 || currentMode == 2 || currentMode == 10)
            {
                #region 出库
                //出库
                if (currentMode == 4 || currentMode == 2 || currentMode == 10)
                {
                    if (currentMode == 2 || currentMode == 10)
                    {
                        switch (currentMode)
                        {
                            case 2:
                                scmodel.WorkModel = 5; break;
                            case 10:
                                scmodel.WorkModel = 9; break;
                            default:
                                break;
                        }

                        scmodel.UpdateTime = DateTime.Now;
                        await ScUpdateScWorkModelInfoAsync(scmodel);
                    }

                    var exp = Expressionable.Create<WorkTaskInfo, RouteDetailInfo>();
                    exp.AndIF(true, (wti, ri) => ri.FromEquipment == scCode);
                    exp.AndIF(true, (wti, ri) => wti.TaskState == EnumTaskState.Initial || wti.TaskState == EnumTaskState.Executing);
                    exp.AndIF(true, (wti, ri) => wti.CurrentDetailTaskState == EnumDetailTaskState.Init);
                    exp.AndIF(true, (wti, ri) => wti.CurrentDispatchType == EnumDispatchType.SC_DOWN || wti.CurrentDispatchType == EnumDispatchType.SC_CROSS);

                    var wmstasks = await _WorkTaskInfoRepository.AsSugarClient()
                    .Queryable<WorkTaskInfo, RouteDetailInfo>((wti, ri) => new JoinQueryInfos(JoinType.Inner, wti.CurrentRounteDetailID == ri.ID))
                    .Where(exp.ToExpression()).OrderBy((wti, ri) => wti.Priority, OrderByType.Desc).OrderBy((wti, ri) => wti.SaveTime, OrderByType.Asc)
                    .Select((wti, ri) => new WCSWorkTaskInfoDto()
                    {
                        ID = wti.ID,
                        RouteID = wti.RouteID,
                        Priority = wti.Priority,
                        PalletCode = wti.PalletCode,
                        TaskCode = wti.TaskCode,
                        TaskProcessState = wti.TaskProcessState,
                        TaskState = wti.TaskState,
                        TaskType = wti.TaskType,
                        SaveTime = wti.SaveTime,
                        UpdateTime = wti.UpdateTime,
                        WmsTaskCode = wti.WmsTaskCode,
                        DependWmsTaskCode = wti.DependWmsTaskCode,
                        WmsFromStation = wti.WmsFromStation,
                        WmsFromPosition = wti.WmsFromPosition.ToString(),
                        WmsToStation = wti.WmsToStation,
                        WmsToPosition = wti.WmsToPosition,
                        CurrentRounteDetailID = wti.CurrentRounteDetailID,
                        CurrentDetailTaskState = wti.CurrentDetailTaskState,
                        CurrentDispatchType = wti.CurrentDispatchType,
                        CurrentFromEquipment = wti.CurrentFromEquipment,
                        CurrentFromCargo = wti.CurrentFromCargo,
                        CurrentToEquipment = wti.CurrentToEquipment,
                        CurrentToCargo = wti.CurrentToCargo,
                        CurrentCreateTime = wti.CurrentCreateTime,
                        CurrentUpdateTime = wti.CurrentUpdateTime
                    })
                    .ToListAsync();

                    if (_LogUtil.LogOpen == "1")
                    {
                        _LogUtil.Debug($"2.获取{scCode}出库任务");
                    }
                    if (wmstasks.Count > 0)
                    {
                        #region 重复任务
                        var tasksame = wmstasks.GroupBy(x => x.WmsTaskCode)
                                                .Where(g => g.Count() > 1)
                                                .Select(y => y)
                                                .ToList();
                        //删除重复的任务
                        if (tasksame.Count != 0 && tasksame != null)
                        {
                            foreach (var tasks in tasksame)
                            {
                                var task = tasks.AsEnumerable().ToList();
                                task.Remove(task.First());
                                foreach (var item in task)
                                {
                                    wmstasks.Remove(item);
                                }

                                var tts = _mapper.Map<List<WCSWorkTaskInfoDto>, List<WorkTaskInfo>>(task);
                                await _WorkTaskInfoRepository.AsSugarClient().Deleteable(tts).ExecuteCommandAsync();
                            }

                        }
                        #endregion

                        foreach (var temp in wmstasks)
                        {
                            try
                            {
                                PlanarStateBO dostation = planarStateBOs.Find(it => it.EquipmentCode == temp.CurrentToEquipment);
                                if (dostation == null)
                                {
                                    runLogInfo.RunLog = $"{temp.CurrentToEquipment} 没有配置交接台信息";
                                    await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                                    continue;
                                }

                                if (dostation.PalletBarcode.Trim().Length == 0 && dostation.Reserve == 0 && dostation.ActionType == 3)
                                {
                                    return temp;
                                }
                                else
                                {
                                    runLogInfo.RunLog = $"交接台{temp.CurrentToEquipment}设备状态占位";
                                    await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                                    continue;
                                }
                            }
                            catch (Exception ex)
                            {
                                runLogInfo.RunLog = $"SC设备{scCode} 配置的{ex.Message}";
                                await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                            }
                        }
                    }
                    else
                    {
                        switch (currentMode)
                        {
                            case 2:
                                currentMode = 5; break;
                            case 10:
                                currentMode = 9; break;

                            default:
                                break;
                        }

                    }
                }
                //移库
                if (currentMode == 6 || currentMode == 5 || currentMode == 8)
                {
                    if (currentMode == 5 || currentMode == 8)
                    {
                        switch (currentMode)
                        {
                            case 5:
                                scmodel.WorkModel = 1; break;
                            case 8:
                                scmodel.WorkModel = 7; break;
                            default:
                                break;
                        }
                        scmodel.UpdateTime = DateTime.Now;
                        await ScUpdateScWorkModelInfoAsync(scmodel);
                    }

                    var exp = Expressionable.Create<WorkTaskInfo, RouteDetailInfo>();
                    exp.AndIF(true, (wti, ri) => ri.ToEquipment == scCode);//哪台堆垛机
                    exp.AndIF(true, (wti, ri) => wti.TaskState == EnumTaskState.Executing || wti.TaskState == EnumTaskState.Initial);
                    exp.AndIF(true, (wti, ri) => wti.CurrentDetailTaskState == EnumDetailTaskState.Init);
                    exp.AndIF(true, (wti, ri) => wti.CurrentDispatchType == EnumDispatchType.SC_MOVE);

                    var wmstasks = await _WorkTaskInfoRepository.AsSugarClient()
                    .Queryable<WorkTaskInfo, RouteDetailInfo>((wti, ri) => new JoinQueryInfos(JoinType.Inner, wti.CurrentRounteDetailID == ri.ID))
                    .Where(exp.ToExpression())
                    .OrderBy(wti => wti.Priority, OrderByType.Desc)
                    .OrderBy(wti => wti.SaveTime, OrderByType.Asc)
                    .Select((wti, ri) => new WCSWorkTaskInfoDto()
                    {
                        ID = wti.ID,
                        RouteID = wti.RouteID,
                        Priority = wti.Priority,
                        PalletCode = wti.PalletCode,
                        TaskCode = wti.TaskCode,
                        TaskProcessState = wti.TaskProcessState,
                        TaskState = wti.TaskState,
                        TaskType = wti.TaskType,
                        SaveTime = wti.SaveTime,
                        UpdateTime = wti.UpdateTime,
                        WmsTaskCode = wti.WmsTaskCode,
                        DependWmsTaskCode = wti.DependWmsTaskCode,
                        WmsFromStation = wti.WmsFromStation,
                        WmsFromPosition = wti.WmsFromPosition.ToString(),
                        WmsToStation = wti.WmsToStation,
                        WmsToPosition = wti.WmsToPosition,
                        CurrentRounteDetailID = wti.CurrentRounteDetailID,
                        CurrentDetailTaskState = wti.CurrentDetailTaskState,
                        CurrentDispatchType = wti.CurrentDispatchType,
                        CurrentFromEquipment = wti.CurrentFromEquipment,
                        CurrentFromCargo = wti.CurrentFromCargo,
                        CurrentToEquipment = wti.CurrentToEquipment,
                        CurrentToCargo = wti.CurrentToCargo,
                        CurrentCreateTime = wti.CurrentCreateTime,
                        CurrentUpdateTime = wti.CurrentUpdateTime
                    })
                    .ToListAsync();

                    if (_LogUtil.LogOpen == "1")
                    {
                        _LogUtil.Debug($"2.获取{scCode}移库任务");
                    }

                    if (wmstasks.Count > 0)
                    {
                        return wmstasks.First();

                    }
                    else
                    {
                        if (currentMode == 5 || currentMode == 8)
                        {
                            switch (currentMode)
                            {
                                case 5:
                                    currentMode = 1; break;
                                case 8:
                                    currentMode = 7; break;
                                default:
                                    break;
                            }
                        }
                    }

                }
                //入库
                if (currentMode == 3 || currentMode == 1 || currentMode == 7 || currentMode == 9)
                {
                    if (currentMode == 1 || currentMode == 7 || currentMode == 9)
                    {
                        switch (currentMode)
                        {
                            case 1:
                                scmodel.WorkModel = 2; break;
                            case 7:
                                scmodel.WorkModel = 8; break;
                            case 9:
                                scmodel.WorkModel = 10; break;
                            default:
                                break;
                        }
                        scmodel.UpdateTime = DateTime.Now;
                        await ScUpdateScWorkModelInfoAsync(scmodel);
                    }
                    var exp = Expressionable.Create<WorkTaskInfo, RouteDetailInfo>();
                    exp.AndIF(true, (wti, ri) => wti.CurrentDispatchType == EnumDispatchType.SC_UP);
                    exp.AndIF(true, (wti, ri) => ri.ToEquipment == scCode);
                    exp.AndIF(true, (wti, ri) => wti.TaskState == EnumTaskState.Executing || wti.TaskState == EnumTaskState.Initial);
                    exp.AndIF(true, (wti, ri) => wti.CurrentDetailTaskState == EnumDetailTaskState.Init);

                    var wmstasks = await _WorkTaskInfoRepository.AsSugarClient()
                    .Queryable<WorkTaskInfo, RouteDetailInfo>((wti, ri) => new JoinQueryInfos(JoinType.Inner, wti.CurrentRounteDetailID == ri.ID))
                    .Where(exp.ToExpression()).OrderBy((wti, ri) => wti.Priority, OrderByType.Desc).OrderBy((wti, ri) => wti.CurrentUpdateTime, OrderByType.Asc)
                    .Select((wti, ri) => new WCSWorkTaskInfoDto()
                    {
                        ID = wti.ID,
                        RouteID = wti.RouteID,
                        Priority = wti.Priority,
                        PalletCode = wti.PalletCode,
                        TaskCode = wti.TaskCode,
                        TaskProcessState = wti.TaskProcessState,
                        TaskState = wti.TaskState,
                        TaskType = wti.TaskType,
                        SaveTime = wti.SaveTime,
                        UpdateTime = wti.UpdateTime,
                        WmsTaskCode = wti.WmsTaskCode,
                        DependWmsTaskCode = wti.DependWmsTaskCode,
                        WmsFromStation = wti.WmsFromStation,
                        WmsFromPosition = wti.WmsFromPosition.ToString(),
                        WmsToStation = wti.WmsToStation,
                        WmsToPosition = wti.WmsToPosition,
                        CurrentRounteDetailID = wti.CurrentRounteDetailID,
                        CurrentDetailTaskState = wti.CurrentDetailTaskState,
                        CurrentDispatchType = wti.CurrentDispatchType,
                        CurrentFromEquipment = wti.CurrentFromEquipment,
                        CurrentFromCargo = wti.CurrentFromCargo,
                        CurrentToEquipment = wti.CurrentToEquipment,
                        CurrentToCargo = wti.CurrentToCargo,
                        CurrentCreateTime = wti.CurrentCreateTime,
                        CurrentUpdateTime = wti.CurrentUpdateTime
                    })
                    .ToListAsync();

                    if (_LogUtil.LogOpen == "1")
                    {
                        _LogUtil.Debug($"2.获取{scCode}入库任务");
                    }

                    if (wmstasks.Count > 0)
                    {
                        //拿到任务跟入库台信息对比一下
                        var firstWorkTask = wmstasks.First();
                        //拿到当前任务入库台的设备号报文信息
                        PlanarStateBO puStationBo = planarStateBOs.Find(it => it.EquipmentCode.ToString() == firstWorkTask.CurrentFromEquipment);
                        if (puStationBo == null)
                        {
                            runLogInfo.RunLog = $"入库台 {firstWorkTask.CurrentFromEquipment} 没有配置交接台信息";
                            await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                            //如果没有配置入库台占位报文，则先返回第一条任务
                            return firstWorkTask;
                        }
                        //判断当前任务是否是入库台的任务
                        if (puStationBo.TaskCode == firstWorkTask.TaskCode && puStationBo.PalletBarcode.Trim() == firstWorkTask.PalletCode)
                        {
                            return firstWorkTask;
                        }
                        else
                        {
                            //拿到入库台的任务和托盘码
                            var tempTask = wmstasks.Find(it => it.PalletCode == puStationBo.PalletBarcode.ToString() && it.TaskCode == puStationBo.TaskCode);
                            if (tempTask != null)
                            {
                                return tempTask;
                            }
                            else
                            {
                                runLogInfo.RunLog = $"入库台 {firstWorkTask.CurrentFromEquipment} 托盘任务异常，请检查入库台信息和任务！";
                                await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                            }
                        }
                    }
                    else
                    {
                        switch (currentMode)
                        {
                            case 1:
                                currentMode = 2; break;
                            case 7:
                                currentMode = 8; break;
                            case 9:
                                currentMode = 10; break;

                            default:
                                break;
                        }


                    }
                }
                #endregion
                if (_LogUtil.LogOpen == "1")
                {
                    _LogUtil.Debug($"2.获取{scCode}出库完成，不存在任务");
                }
                return null;
            }
            //移库
            if (currentMode == 6 || currentMode == 5 || currentMode == 8)
            {
                #region 移库
                //移库
                if (currentMode == 6 || currentMode == 5 || currentMode == 8)
                {
                    if (currentMode == 5 || currentMode == 8)
                    {
                        switch (currentMode)
                        {
                            case 5:
                                scmodel.WorkModel = 1; break;
                            case 8:
                                scmodel.WorkModel = 7; break;
                            default:
                                break;
                        }
                        scmodel.UpdateTime = DateTime.Now;
                        await ScUpdateScWorkModelInfoAsync(scmodel);
                    }

                    var exp = Expressionable.Create<WorkTaskInfo, RouteDetailInfo>();
                    exp.AndIF(true, (wti, ri) => ri.ToEquipment == scCode);//哪台堆垛机
                    exp.AndIF(true, (wti, ri) => wti.TaskState == EnumTaskState.Executing || wti.TaskState == EnumTaskState.Initial);
                    exp.AndIF(true, (wti, ri) => wti.CurrentDetailTaskState == EnumDetailTaskState.Init);
                    exp.AndIF(true, (wti, ri) => wti.CurrentDispatchType == EnumDispatchType.SC_MOVE);

                    var wmstasks = await _WorkTaskInfoRepository.AsSugarClient()
                    .Queryable<WorkTaskInfo, RouteDetailInfo>((wti, ri) => new JoinQueryInfos(JoinType.Inner, wti.CurrentRounteDetailID == ri.ID))
                    .Where(exp.ToExpression())
                    .OrderBy(wti => wti.Priority, OrderByType.Desc)
                    .OrderBy(wti => wti.SaveTime, OrderByType.Asc)
                    .Select((wti, ri) => new WCSWorkTaskInfoDto()
                    {
                        ID = wti.ID,
                        RouteID = wti.RouteID,
                        Priority = wti.Priority,
                        PalletCode = wti.PalletCode,
                        TaskCode = wti.TaskCode,
                        TaskProcessState = wti.TaskProcessState,
                        TaskState = wti.TaskState,
                        TaskType = wti.TaskType,
                        SaveTime = wti.SaveTime,
                        UpdateTime = wti.UpdateTime,
                        WmsTaskCode = wti.WmsTaskCode,
                        DependWmsTaskCode = wti.DependWmsTaskCode,
                        WmsFromStation = wti.WmsFromStation,
                        WmsFromPosition = wti.WmsFromPosition.ToString(),
                        WmsToStation = wti.WmsToStation,
                        WmsToPosition = wti.WmsToPosition,
                        CurrentRounteDetailID = wti.CurrentRounteDetailID,
                        CurrentDetailTaskState = wti.CurrentDetailTaskState,
                        CurrentDispatchType = wti.CurrentDispatchType,
                        CurrentFromEquipment = wti.CurrentFromEquipment,
                        CurrentFromCargo = wti.CurrentFromCargo,
                        CurrentToEquipment = wti.CurrentToEquipment,
                        CurrentToCargo = wti.CurrentToCargo,
                        CurrentCreateTime = wti.CurrentCreateTime,
                        CurrentUpdateTime = wti.CurrentUpdateTime
                    })
                    .ToListAsync();

                    if (_LogUtil.LogOpen == "1")
                    {
                        _LogUtil.Debug($"3.获取{scCode}移库任务");
                    }

                    if (wmstasks.Count > 0)
                    {
                        return wmstasks.First();

                    }
                    else
                    {
                        if (currentMode == 5 || currentMode == 8)
                        {
                            switch (currentMode)
                            {
                                case 5:
                                    currentMode = 1; break;
                                case 8:
                                    currentMode = 7; break;
                                default:
                                    break;
                            }
                        }
                    }

                }
                //入库
                if (currentMode == 3 || currentMode == 1 || currentMode == 7 || currentMode == 9)
                {
                    if (currentMode == 1 || currentMode == 7 || currentMode == 9)
                    {
                        switch (currentMode)
                        {
                            case 1:
                                scmodel.WorkModel = 2; break;
                            case 7:
                                scmodel.WorkModel = 8; break;
                            case 9:
                                scmodel.WorkModel = 10; break;
                            default:
                                break;
                        }
                        scmodel.UpdateTime = DateTime.Now;
                        await ScUpdateScWorkModelInfoAsync(scmodel);
                    }
                    var exp = Expressionable.Create<WorkTaskInfo, RouteDetailInfo>();
                    exp.AndIF(true, (wti, ri) => wti.CurrentDispatchType == EnumDispatchType.SC_UP);
                    exp.AndIF(true, (wti, ri) => ri.ToEquipment == scCode);
                    exp.AndIF(true, (wti, ri) => wti.TaskState == EnumTaskState.Executing || wti.TaskState == EnumTaskState.Initial);
                    exp.AndIF(true, (wti, ri) => wti.CurrentDetailTaskState == EnumDetailTaskState.Init);

                    var wmstasks = await _WorkTaskInfoRepository.AsSugarClient()
                    .Queryable<WorkTaskInfo, RouteDetailInfo>((wti, ri) => new JoinQueryInfos(JoinType.Inner, wti.CurrentRounteDetailID == ri.ID))
                    .Where(exp.ToExpression()).OrderBy((wti, ri) => wti.Priority, OrderByType.Desc).OrderBy((wti, ri) => wti.CurrentUpdateTime, OrderByType.Asc)
                    .Select((wti, ri) => new WCSWorkTaskInfoDto()
                    {
                        ID = wti.ID,
                        RouteID = wti.RouteID,
                        Priority = wti.Priority,
                        PalletCode = wti.PalletCode,
                        TaskCode = wti.TaskCode,
                        TaskProcessState = wti.TaskProcessState,
                        TaskState = wti.TaskState,
                        TaskType = wti.TaskType,
                        SaveTime = wti.SaveTime,
                        UpdateTime = wti.UpdateTime,
                        WmsTaskCode = wti.WmsTaskCode,
                        DependWmsTaskCode = wti.DependWmsTaskCode,
                        WmsFromStation = wti.WmsFromStation,
                        WmsFromPosition = wti.WmsFromPosition.ToString(),
                        WmsToStation = wti.WmsToStation,
                        WmsToPosition = wti.WmsToPosition,
                        CurrentRounteDetailID = wti.CurrentRounteDetailID,
                        CurrentDetailTaskState = wti.CurrentDetailTaskState,
                        CurrentDispatchType = wti.CurrentDispatchType,
                        CurrentFromEquipment = wti.CurrentFromEquipment,
                        CurrentFromCargo = wti.CurrentFromCargo,
                        CurrentToEquipment = wti.CurrentToEquipment,
                        CurrentToCargo = wti.CurrentToCargo,
                        CurrentCreateTime = wti.CurrentCreateTime,
                        CurrentUpdateTime = wti.CurrentUpdateTime
                    })
                    .ToListAsync();

                    if (_LogUtil.LogOpen == "1")
                    {
                        _LogUtil.Debug($"3.获取{scCode}入库任务");
                    }

                    if (wmstasks.Count > 0)
                    {
                        //拿到任务跟入库台信息对比一下
                        var firstWorkTask = wmstasks.First();
                        //拿到当前任务入库台的设备号报文信息
                        PlanarStateBO puStationBo = planarStateBOs.Find(it => it.EquipmentCode.ToString() == firstWorkTask.CurrentFromEquipment);
                        if (puStationBo == null)
                        {
                            runLogInfo.RunLog = $"入库台 {firstWorkTask.CurrentFromEquipment} 没有配置交接台信息";
                            await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                            //如果没有配置入库台占位报文，则先返回第一条任务
                            return firstWorkTask;
                        }
                        //判断当前任务是否是入库台的任务
                        if (puStationBo.TaskCode == firstWorkTask.TaskCode && puStationBo.PalletBarcode.Trim() == firstWorkTask.PalletCode)
                        {
                            return firstWorkTask;
                        }
                        else
                        {
                            //拿到入库台的任务和托盘码
                            var tempTask = wmstasks.Find(it => it.PalletCode == puStationBo.PalletBarcode.ToString() && it.TaskCode == puStationBo.TaskCode);
                            if (tempTask != null)
                            {
                                return tempTask;
                            }
                            else
                            {
                                runLogInfo.RunLog = $"入库台 {firstWorkTask.CurrentFromEquipment} 托盘任务异常，请检查入库台信息和任务！";
                                await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                            }
                        }
                    }
                    else
                    {
                        switch (currentMode)
                        {
                            case 1:
                                currentMode = 2; break;
                            case 7:
                                currentMode = 8; break;
                            case 9:
                                currentMode = 10; break;

                            default:
                                break;
                        }


                    }
                }
                //出库
                if (currentMode == 4 || currentMode == 2 || currentMode == 10)
                {
                    if (currentMode == 2 || currentMode == 10)
                    {
                        switch (currentMode)
                        {
                            case 2:
                                scmodel.WorkModel = 5; break;
                            case 10:
                                scmodel.WorkModel = 9; break;
                            default:
                                break;
                        }

                        scmodel.UpdateTime = DateTime.Now;
                        await ScUpdateScWorkModelInfoAsync(scmodel);
                    }

                    var exp = Expressionable.Create<WorkTaskInfo, RouteDetailInfo>();
                    exp.AndIF(true, (wti, ri) => ri.FromEquipment == scCode);
                    exp.AndIF(true, (wti, ri) => wti.TaskState == EnumTaskState.Initial || wti.TaskState == EnumTaskState.Executing);
                    exp.AndIF(true, (wti, ri) => wti.CurrentDetailTaskState == EnumDetailTaskState.Init);
                    exp.AndIF(true, (wti, ri) => wti.CurrentDispatchType == EnumDispatchType.SC_DOWN || wti.CurrentDispatchType == EnumDispatchType.SC_CROSS);

                    var wmstasks = await _WorkTaskInfoRepository.AsSugarClient()
                    .Queryable<WorkTaskInfo, RouteDetailInfo>((wti, ri) => new JoinQueryInfos(JoinType.Inner, wti.CurrentRounteDetailID == ri.ID))
                    .Where(exp.ToExpression()).OrderBy((wti, ri) => wti.Priority, OrderByType.Desc).OrderBy((wti, ri) => wti.SaveTime, OrderByType.Asc)
                    .Select((wti, ri) => new WCSWorkTaskInfoDto()
                    {
                        ID = wti.ID,
                        RouteID = wti.RouteID,
                        Priority = wti.Priority,
                        PalletCode = wti.PalletCode,
                        TaskCode = wti.TaskCode,
                        TaskProcessState = wti.TaskProcessState,
                        TaskState = wti.TaskState,
                        TaskType = wti.TaskType,
                        SaveTime = wti.SaveTime,
                        UpdateTime = wti.UpdateTime,
                        WmsTaskCode = wti.WmsTaskCode,
                        DependWmsTaskCode = wti.DependWmsTaskCode,
                        WmsFromStation = wti.WmsFromStation,
                        WmsFromPosition = wti.WmsFromPosition.ToString(),
                        WmsToStation = wti.WmsToStation,
                        WmsToPosition = wti.WmsToPosition,
                        CurrentRounteDetailID = wti.CurrentRounteDetailID,
                        CurrentDetailTaskState = wti.CurrentDetailTaskState,
                        CurrentDispatchType = wti.CurrentDispatchType,
                        CurrentFromEquipment = wti.CurrentFromEquipment,
                        CurrentFromCargo = wti.CurrentFromCargo,
                        CurrentToEquipment = wti.CurrentToEquipment,
                        CurrentToCargo = wti.CurrentToCargo,
                        CurrentCreateTime = wti.CurrentCreateTime,
                        CurrentUpdateTime = wti.CurrentUpdateTime
                    })
                    .ToListAsync();

                    if (_LogUtil.LogOpen == "1")
                    {
                        _LogUtil.Debug($"3.获取{scCode}出库任务");
                    }
                    if (wmstasks.Count > 0)
                    {
                        #region 重复任务
                        var tasksame = wmstasks.GroupBy(x => x.WmsTaskCode)
                                                .Where(g => g.Count() > 1)
                                                .Select(y => y)
                                                .ToList();
                        //删除重复的任务
                        if (tasksame.Count != 0 && tasksame != null)
                        {
                            foreach (var tasks in tasksame)
                            {
                                var task = tasks.AsEnumerable().ToList();
                                task.Remove(task.First());
                                foreach (var item in task)
                                {
                                    wmstasks.Remove(item);
                                }

                                var tts = _mapper.Map<List<WCSWorkTaskInfoDto>, List<WorkTaskInfo>>(task);
                                await _WorkTaskInfoRepository.AsSugarClient().Deleteable(tts).ExecuteCommandAsync();
                            }

                        }
                        #endregion

                        foreach (var temp in wmstasks)
                        {
                            try
                            {
                                PlanarStateBO dostation = planarStateBOs.Find(it => it.EquipmentCode == temp.CurrentToEquipment);
                                if (dostation == null)
                                {
                                    runLogInfo.RunLog = $"{temp.CurrentToEquipment} 没有配置交接台信息";
                                    await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                                    continue;
                                }

                                if (dostation.PalletBarcode.Trim().Length == 0 && dostation.Reserve == 0 && dostation.ActionType == 3)
                                {
                                    return temp;
                                }
                                else
                                {
                                    runLogInfo.RunLog = $"交接台{temp.CurrentToEquipment}设备状态占位";
                                    await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                                    continue;
                                }
                            }
                            catch (Exception ex)
                            {
                                runLogInfo.RunLog = $"SC设备{scCode} 配置的{ex.Message}";
                                await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                            }
                        }
                    }
                    else
                    {
                        switch (currentMode)
                        {
                            case 2:
                                currentMode = 5; break;
                            case 10:
                                currentMode = 9; break;

                            default:
                                break;
                        }

                    }
                }
                #endregion
                if (_LogUtil.LogOpen == "1")
                {
                    _LogUtil.Debug($"3.获取{scCode}移库完成，不存在任务");
                }
                return null;
            }

            #region OLD
            ////入库
            //if (currentMode == 3 || currentMode == 1 || currentMode == 7 || currentMode == 9)
            //{
            //    if (currentMode == 1 || currentMode == 7 || currentMode == 9)
            //    {
            //        switch (currentMode)
            //        {
            //            case 1:
            //                scmodel.WorkModel = 2; break;
            //            case 7:
            //                scmodel.WorkModel = 8; break;
            //            case 9:
            //                scmodel.WorkModel = 10; break;
            //            default:
            //                break;
            //        }
            //        scmodel.UpdateTime = DateTime.Now;
            //        await ScUpdateScWorkModelInfoAsync(scmodel);
            //    }
            //    var exp = Expressionable.Create<WorkTaskInfo, RouteDetailInfo>();
            //    exp.AndIF(true, (wti, ri) => wti.CurrentDispatchType == EnumDispatchType.SC_UP);
            //    exp.AndIF(true, (wti, ri) => ri.ToEquipment == scCode);
            //    exp.AndIF(true, (wti, ri) => wti.TaskState == EnumTaskState.Executing || wti.TaskState == EnumTaskState.Initial);
            //    exp.AndIF(true, (wti, ri) => wti.CurrentDetailTaskState == EnumDetailTaskState.Init);

            //    var wmstasks = await _WorkTaskInfoRepository.AsSugarClient()
            //    .Queryable<WorkTaskInfo, RouteDetailInfo>((wti, ri) => new JoinQueryInfos(JoinType.Inner, wti.CurrentRounteDetailID == ri.ID))
            //    .Where(exp.ToExpression()).OrderBy((wti, ri) => wti.Priority, OrderByType.Desc).OrderBy((wti, ri) => wti.CurrentUpdateTime, OrderByType.Asc)
            //    .Select((wti, ri) => new WCSWorkTaskInfoDto()
            //    {
            //        ID = wti.ID,
            //        RouteID = wti.RouteID,
            //        Priority = wti.Priority,
            //        PalletCode = wti.PalletCode,
            //        TaskCode = wti.TaskCode,
            //        TaskProcessState = wti.TaskProcessState,
            //        TaskState = wti.TaskState,
            //        TaskType = wti.TaskType,
            //        SaveTime = wti.SaveTime,
            //        UpdateTime = wti.UpdateTime,
            //        WmsTaskCode = wti.WmsTaskCode,
            //        DependWmsTaskCode = wti.DependWmsTaskCode,
            //        WmsFromStation = wti.WmsFromStation,
            //        WmsFromPosition = wti.WmsFromPosition.ToString(),
            //        WmsToStation = wti.WmsToStation,
            //        WmsToPosition = wti.WmsToPosition,
            //        CurrentRounteDetailID = wti.CurrentRounteDetailID,
            //        CurrentDetailTaskState = wti.CurrentDetailTaskState,
            //        CurrentDispatchType = wti.CurrentDispatchType,
            //        CurrentFromEquipment = wti.CurrentFromEquipment,
            //        CurrentFromCargo = wti.CurrentFromCargo,
            //        CurrentToEquipment = wti.CurrentToEquipment,
            //        CurrentToCargo = wti.CurrentToCargo,
            //        CurrentCreateTime = wti.CurrentCreateTime,
            //        CurrentUpdateTime = wti.CurrentUpdateTime
            //    })
            //    .ToListAsync();

            //    if (_LogUtil.LogOpen == "1")
            //    {
            //        _LogUtil.Debug($"获取{scCode}入库任务");
            //    }

            //    if (wmstasks.Count > 0)
            //    {
            //        //拿到任务跟入库台信息对比一下
            //        var firstWorkTask = wmstasks.First();
            //        //拿到当前任务入库台的设备号报文信息
            //        PlanarStateBO puStationBo = planarStateBOs.Find(it => it.EquipmentCode.ToString() == firstWorkTask.CurrentFromEquipment);
            //        if (puStationBo == null)
            //        {
            //            runLogInfo.RunLog = $"入库台 {firstWorkTask.CurrentFromEquipment} 没有配置交接台信息";
            //            await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
            //            //如果没有配置入库台占位报文，则先返回第一条任务
            //            return firstWorkTask;
            //        }
            //        //判断当前任务是否是入库台的任务
            //        if (puStationBo.TaskCode == firstWorkTask.TaskCode && puStationBo.PalletBarcode.Trim() == firstWorkTask.PalletCode)
            //        {
            //            return firstWorkTask;
            //        }
            //        else
            //        {
            //            //拿到入库台的任务和托盘码
            //            var tempTask = wmstasks.Find(it => it.PalletCode == puStationBo.PalletBarcode.ToString() && it.TaskCode == puStationBo.TaskCode);
            //            if (tempTask != null)
            //            {
            //                return tempTask;
            //            }
            //            else
            //            {
            //                runLogInfo.RunLog = $"入库台 {firstWorkTask.CurrentFromEquipment} 托盘任务异常，请检查入库台信息和任务！";
            //                await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
            //            }
            //        }
            //    }
            //    else
            //    {
            //        switch (currentMode)
            //        {
            //            case 1:
            //                currentMode = 2; break;
            //            case 7:
            //                currentMode = 8; break;
            //            case 9:
            //                currentMode = 10; break;

            //            default:
            //                break;
            //        }


            //    }
            //}
            ////出库
            //if (currentMode == 4 || currentMode == 2 || currentMode == 10)
            //{
            //    if (currentMode == 2 || currentMode == 10)
            //    {
            //        switch (currentMode)
            //        {
            //            case 2:
            //                scmodel.WorkModel = 5; break;
            //            case 10:
            //                scmodel.WorkModel = 9; break;
            //            default:
            //                break;
            //        }

            //        scmodel.UpdateTime = DateTime.Now;
            //        await ScUpdateScWorkModelInfoAsync(scmodel);
            //    }

            //    var exp = Expressionable.Create<WorkTaskInfo, RouteDetailInfo>();
            //    exp.AndIF(true, (wti, ri) => ri.FromEquipment == scCode);
            //    exp.AndIF(true, (wti, ri) => wti.TaskState == EnumTaskState.Initial || wti.TaskState == EnumTaskState.Executing);
            //    exp.AndIF(true, (wti, ri) => wti.CurrentDetailTaskState == EnumDetailTaskState.Init);
            //    exp.AndIF(true, (wti, ri) => wti.CurrentDispatchType == EnumDispatchType.SC_DOWN || wti.CurrentDispatchType == EnumDispatchType.SC_CROSS);

            //    var wmstasks = await _WorkTaskInfoRepository.AsSugarClient()
            //    .Queryable<WorkTaskInfo, RouteDetailInfo>((wti, ri) => new JoinQueryInfos(JoinType.Inner, wti.CurrentRounteDetailID == ri.ID))
            //    .Where(exp.ToExpression()).OrderBy((wti, ri) => wti.Priority, OrderByType.Desc).OrderBy((wti, ri) => wti.SaveTime, OrderByType.Asc)
            //    .Select((wti, ri) => new WCSWorkTaskInfoDto()
            //    {
            //        ID = wti.ID,
            //        RouteID = wti.RouteID,
            //        Priority = wti.Priority,
            //        PalletCode = wti.PalletCode,
            //        TaskCode = wti.TaskCode,
            //        TaskProcessState = wti.TaskProcessState,
            //        TaskState = wti.TaskState,
            //        TaskType = wti.TaskType,
            //        SaveTime = wti.SaveTime,
            //        UpdateTime = wti.UpdateTime,
            //        WmsTaskCode = wti.WmsTaskCode,
            //        DependWmsTaskCode = wti.DependWmsTaskCode,
            //        WmsFromStation = wti.WmsFromStation,
            //        WmsFromPosition = wti.WmsFromPosition.ToString(),
            //        WmsToStation = wti.WmsToStation,
            //        WmsToPosition = wti.WmsToPosition,
            //        CurrentRounteDetailID = wti.CurrentRounteDetailID,
            //        CurrentDetailTaskState = wti.CurrentDetailTaskState,
            //        CurrentDispatchType = wti.CurrentDispatchType,
            //        CurrentFromEquipment = wti.CurrentFromEquipment,
            //        CurrentFromCargo = wti.CurrentFromCargo,
            //        CurrentToEquipment = wti.CurrentToEquipment,
            //        CurrentToCargo = wti.CurrentToCargo,
            //        CurrentCreateTime = wti.CurrentCreateTime,
            //        CurrentUpdateTime = wti.CurrentUpdateTime
            //    })
            //    .ToListAsync();

            //    if (_LogUtil.LogOpen == "1")
            //    {
            //        _LogUtil.Debug($"获取{scCode}出库任务");
            //    }
            //    if (wmstasks.Count > 0)
            //    {
            //        #region 重复任务
            //        var tasksame = wmstasks.GroupBy(x => x.WmsTaskCode)
            //                                .Where(g => g.Count() > 1)
            //                                .Select(y => y)
            //                                .ToList();
            //        //删除重复的任务
            //        if (tasksame.Count != 0 && tasksame != null)
            //        {
            //            foreach (var tasks in tasksame)
            //            {
            //                var task = tasks.AsEnumerable().ToList();
            //                task.Remove(task.First());
            //                foreach (var item in task)
            //                {
            //                    wmstasks.Remove(item);
            //                }

            //                var tts = _mapper.Map<List<WCSWorkTaskInfoDto>, List<WorkTaskInfo>>(task);
            //                await _WorkTaskInfoRepository.AsSugarClient().Deleteable(tts).ExecuteCommandAsync();
            //            }

            //        }
            //        #endregion

            //        foreach (var temp in wmstasks)
            //        {
            //            try
            //            {
            //                PlanarStateBO dostation = planarStateBOs.Find(it => it.EquipmentCode == temp.CurrentToEquipment);
            //                if (dostation == null)
            //                {
            //                    runLogInfo.RunLog = $"{temp.CurrentToEquipment} 没有配置交接台信息";
            //                    await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
            //                    continue;
            //                }

            //                if (dostation.PalletBarcode.Trim().Length == 0 && dostation.Reserve == 0 && dostation.ActionType == 3)
            //                {
            //                    return temp;
            //                }
            //                else
            //                {
            //                    runLogInfo.RunLog = $"交接台{temp.CurrentToEquipment}设备状态占位";
            //                    await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
            //                    continue;
            //                }
            //            }
            //            catch (Exception ex)
            //            {
            //                runLogInfo.RunLog = $"SC设备{scCode} 配置的{ex.Message}";
            //                await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
            //            }
            //        }
            //    }
            //    else
            //    {
            //        switch (currentMode)
            //        {
            //            case 2:
            //                currentMode = 5; break;
            //            case 10:
            //                currentMode = 9; break;

            //            default:
            //                break;
            //        }

            //    }
            //}
            ////移库
            //if (currentMode == 6 || currentMode == 5 || currentMode == 8)
            //{
            //    if (currentMode == 5 || currentMode == 8)
            //    {
            //        switch (currentMode)
            //        {
            //            case 5:
            //                scmodel.WorkModel = 1; break;
            //            case 8:
            //                scmodel.WorkModel = 7; break;
            //            default:
            //                break;
            //        }
            //        scmodel.UpdateTime = DateTime.Now;
            //        await ScUpdateScWorkModelInfoAsync(scmodel);
            //    }

            //    var exp = Expressionable.Create<WorkTaskInfo, RouteDetailInfo>();
            //    exp.AndIF(true, (wti, ri) => ri.ToEquipment == scCode);//哪台堆垛机
            //    exp.AndIF(true, (wti, ri) => wti.TaskState == EnumTaskState.Executing || wti.TaskState == EnumTaskState.Initial);
            //    exp.AndIF(true, (wti, ri) => wti.CurrentDetailTaskState == EnumDetailTaskState.Init);
            //    exp.AndIF(true, (wti, ri) => wti.CurrentDispatchType == EnumDispatchType.SC_MOVE);

            //    var wmstasks = await _WorkTaskInfoRepository.AsSugarClient()
            //    .Queryable<WorkTaskInfo, RouteDetailInfo>((wti, ri) => new JoinQueryInfos(JoinType.Inner, wti.CurrentRounteDetailID == ri.ID))
            //    .Where(exp.ToExpression())
            //    .OrderBy(wti => wti.Priority, OrderByType.Desc)
            //    .OrderBy(wti => wti.SaveTime, OrderByType.Asc)
            //    .Select((wti, ri) => new WCSWorkTaskInfoDto()
            //    {
            //        ID = wti.ID,
            //        RouteID = wti.RouteID,
            //        Priority = wti.Priority,
            //        PalletCode = wti.PalletCode,
            //        TaskCode = wti.TaskCode,
            //        TaskProcessState = wti.TaskProcessState,
            //        TaskState = wti.TaskState,
            //        TaskType = wti.TaskType,
            //        SaveTime = wti.SaveTime,
            //        UpdateTime = wti.UpdateTime,
            //        WmsTaskCode = wti.WmsTaskCode,
            //        DependWmsTaskCode = wti.DependWmsTaskCode,
            //        WmsFromStation = wti.WmsFromStation,
            //        WmsFromPosition = wti.WmsFromPosition.ToString(),
            //        WmsToStation = wti.WmsToStation,
            //        WmsToPosition = wti.WmsToPosition,
            //        CurrentRounteDetailID = wti.CurrentRounteDetailID,
            //        CurrentDetailTaskState = wti.CurrentDetailTaskState,
            //        CurrentDispatchType = wti.CurrentDispatchType,
            //        CurrentFromEquipment = wti.CurrentFromEquipment,
            //        CurrentFromCargo = wti.CurrentFromCargo,
            //        CurrentToEquipment = wti.CurrentToEquipment,
            //        CurrentToCargo = wti.CurrentToCargo,
            //        CurrentCreateTime = wti.CurrentCreateTime,
            //        CurrentUpdateTime = wti.CurrentUpdateTime
            //    })
            //    .ToListAsync();

            //    if (_LogUtil.LogOpen == "1")
            //    {
            //        _LogUtil.Debug($"获取{scCode}移库任务");
            //    }

            //    if (wmstasks.Count > 0)
            //    {
            //        return wmstasks.First();

            //    }
            //    else
            //    {
            //        if (currentMode == 5 || currentMode == 8)
            //        {
            //            switch (currentMode)
            //            {
            //                case 5:
            //                    currentMode = 1; break;
            //                case 8:
            //                    currentMode = 7; break;
            //                default:
            //                    break;
            //            }
            //        }
            //    }

            //}
            #endregion


            #region 弃用
            ////时间排序获取一个最早的任务
            //if (_LogUtil.LogOpen == "1")
            //{
            //    var exp = Expressionable.Create<WorkTaskInfo, RouteDetailInfo>();
            //    exp.AndIF(true, (wti, ri) => (ri.FromEquipment == scCode || ri.ToEquipment == scCode));
            //    exp.AndIF(true, (wti, ri) => wti.TaskState == EnumTaskState.Initial || wti.TaskState == EnumTaskState.Executing);
            //    exp.AndIF(true, (wti, ri) => wti.CurrentDetailTaskState == EnumDetailTaskState.Init);

            //    var wmstasks = await _WorkTaskInfoRepository.AsSugarClient()
            //    .Queryable<WorkTaskInfo, RouteDetailInfo>((wti, ri) => new JoinQueryInfos(JoinType.Inner, wti.CurrentRounteDetailID == ri.ID))
            //    .Where(exp.ToExpression())
            //    .OrderBy((wti, ri) => wti.CurrentCreateTime, OrderByType.Asc)
            //    .Select((wti, ri) => new WCSWorkTaskInfoDto()
            //    {
            //        ID = wti.ID,
            //        RouteID = wti.RouteID,
            //        Priority = wti.Priority,
            //        PalletCode = wti.PalletCode,
            //        TaskCode = wti.TaskCode,
            //        TaskProcessState = wti.TaskProcessState,
            //        TaskState = wti.TaskState,
            //        TaskType = wti.TaskType,
            //        SaveTime = wti.SaveTime,
            //        UpdateTime = wti.UpdateTime,
            //        WmsTaskCode = wti.WmsTaskCode,
            //        DependWmsTaskCode = wti.DependWmsTaskCode,
            //        WmsFromStation = wti.WmsFromStation,
            //        WmsFromPosition = wti.WmsFromPosition.ToString(),
            //        WmsToStation = wti.WmsToStation,
            //        WmsToPosition = wti.WmsToPosition,
            //        CurrentRounteDetailID = wti.CurrentRounteDetailID,
            //        CurrentDetailTaskState = wti.CurrentDetailTaskState,
            //        CurrentDispatchType = wti.CurrentDispatchType,
            //        CurrentFromEquipment = wti.CurrentFromEquipment,
            //        CurrentFromCargo = wti.CurrentFromCargo,
            //        CurrentToEquipment = wti.CurrentToEquipment,
            //        CurrentToCargo = wti.CurrentToCargo,
            //        CurrentCreateTime = wti.CurrentCreateTime,
            //        CurrentUpdateTime = wti.CurrentUpdateTime
            //    })
            //    .ToListAsync();

            //    if (wmstasks.Count > 0)
            //    {
            //        //return wmstasks.First();
            //        foreach (var temp in wmstasks)
            //        {
            //            try
            //            {

            //                if (temp.CurrentDispatchType == EnumDispatchType.SC_DOWN)
            //                {
            //                    PlanarStateBO dostation = planarStateBOs.Find(it => it.EquipmentCode.ToString() == temp.CurrentToEquipment);
            //                    if (dostation == null)
            //                    {
            //                        runLogInfo.RunLog = $"{temp.CurrentToEquipment} 没有配置交接台信息";
            //                        await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
            //                        continue;
            //                    }

            //                    if (dostation.PalletBarcode.Trim().Length == 0 && dostation.Reserve == 0 && dostation.ActionType == 3)
            //                    {
            //                        return temp;
            //                    }
            //                    else
            //                    {
            //                        runLogInfo.RunLog = $"交接台{temp.CurrentToEquipment}设备状态占位";
            //                        await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
            //                        continue;

            //                    }

            //                }
            //                else
            //                {
            //                    return temp;
            //                }

            //            }
            //            catch (Exception ex)
            //            {
            //                runLogInfo.RunLog = $"SC设备{scCode} 配置的{ex.Message}";
            //                await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
            //            }
            //        }
            //    }
            //}
            #endregion



            //throw new Exception($"{scCode}没有出入出库作业");
            return null;
        }


        public async Task<WCSWorkTaskInfoDto> ScGetReEnterWorkTaskInfoAsync(int wcstaskcode)
        {
            var exp = Expressionable.Create<WorkTaskInfo, RouteDetailInfo>();
            exp.AndIF(true, (wti, ri) => wti.TaskCode == wcstaskcode);
            exp.AndIF(true, (wti, ri) => wti.TaskState == EnumTaskState.Executing);
            exp.AndIF(true, (wti, ri) => wti.CurrentDetailTaskState == EnumDetailTaskState.Executing);

            exp.AndIF(true, (wti, ri) => wti.TaskProcessState != EnumTaskProcessState.ErrorOccupied || wti.TaskProcessState != EnumTaskProcessState.ScUnloaded);

            var wCSWorkTaskInfoDto = await _WorkTaskInfoRepository.AsSugarClient()
               .Queryable<WorkTaskInfo, RouteDetailInfo>((wti, ri) => new JoinQueryInfos(JoinType.Inner, wti.CurrentRounteDetailID == ri.ID))
               .Where(exp.ToExpression())
               .Select((wti, ri) => new WCSWorkTaskInfoDto()
               {
                   ID = wti.ID,
                   RouteID = wti.RouteID,
                   Priority = wti.Priority,
                   PalletCode = wti.PalletCode,
                   TaskCode = wti.TaskCode,
                   TaskProcessState = wti.TaskProcessState,
                   TaskState = wti.TaskState,
                   TaskType = wti.TaskType,
                   SaveTime = wti.SaveTime,
                   UpdateTime = wti.UpdateTime,
                   WmsTaskCode = wti.WmsTaskCode,
                   DependWmsTaskCode = wti.DependWmsTaskCode,
                   WmsFromStation = wti.WmsFromStation,
                   WmsFromPosition = wti.WmsFromPosition.ToString(),
                   WmsToStation = wti.WmsToStation,
                   WmsToPosition = wti.WmsToPosition,
                   CurrentRounteDetailID = wti.CurrentRounteDetailID,
                   CurrentDetailTaskState = wti.CurrentDetailTaskState,
                   CurrentDispatchType = wti.CurrentDispatchType,
                   CurrentFromEquipment = wti.CurrentFromEquipment,
                   CurrentFromCargo = wti.CurrentFromCargo,
                   CurrentToEquipment = wti.CurrentToEquipment,
                   CurrentToCargo = wti.CurrentToCargo,
                   CurrentCreateTime = wti.CurrentCreateTime,
                   CurrentUpdateTime = wti.CurrentUpdateTime
               })
               .FirstAsync();

            if (wCSWorkTaskInfoDto != null)
            {
                int sum = await _WorkTaskInfoRepository.AsSugarClient().Updateable<WorkTaskInfo>()
                   .SetColumns(it => new WorkTaskInfo()
                   {
                       TaskProcessState = EnumTaskProcessState.ErrorOccupied,
                       UpdateTime = DateTime.Now
                   })
                   .Where(it => it.ID == wCSWorkTaskInfoDto.ID).ExecuteCommandAsync();
            }

            return wCSWorkTaskInfoDto;
        }

        public async Task<WCSWorkTaskInfoDto> ScGetTakeEmptyWorkTaskInfoAsync(int wcstaskcode)
        {
            var exp = Expressionable.Create<WorkTaskInfo, RouteDetailInfo>();
            exp.AndIF(true, (wti, ri) => wti.TaskCode == wcstaskcode);
            exp.AndIF(true, (wti, ri) => wti.TaskState == EnumTaskState.Executing);
            exp.AndIF(true, (wti, ri) => wti.CurrentDetailTaskState == EnumDetailTaskState.Executing);
            exp.AndIF(true, (wti, ri) => wti.TaskProcessState != EnumTaskProcessState.ErrorEmptyLoad || wti.TaskProcessState != EnumTaskProcessState.ScUnloaded);

            var wCSWorkTaskInfoDto = await _WorkTaskInfoRepository.AsSugarClient()
               .Queryable<WorkTaskInfo, RouteDetailInfo>((wti, ri) => new JoinQueryInfos(JoinType.Inner, wti.CurrentRounteDetailID == ri.ID))
               .Where(exp.ToExpression())
               .Select((wti, ri) => new WCSWorkTaskInfoDto()
               {
                   ID = wti.ID,
                   RouteID = wti.RouteID,
                   Priority = wti.Priority,
                   PalletCode = wti.PalletCode,
                   TaskCode = wti.TaskCode,
                   TaskProcessState = wti.TaskProcessState,
                   TaskState = wti.TaskState,
                   TaskType = wti.TaskType,
                   SaveTime = wti.SaveTime,
                   UpdateTime = wti.UpdateTime,
                   WmsTaskCode = wti.WmsTaskCode,
                   DependWmsTaskCode = wti.DependWmsTaskCode,
                   WmsFromStation = wti.WmsFromStation,
                   WmsFromPosition = wti.WmsFromPosition.ToString(),
                   WmsToStation = wti.WmsToStation,
                   WmsToPosition = wti.WmsToPosition,
                   CurrentRounteDetailID = wti.CurrentRounteDetailID,
                   CurrentDetailTaskState = wti.CurrentDetailTaskState,
                   CurrentDispatchType = wti.CurrentDispatchType,
                   CurrentFromEquipment = wti.CurrentFromEquipment,
                   CurrentFromCargo = wti.CurrentFromCargo,
                   CurrentToEquipment = wti.CurrentToEquipment,
                   CurrentToCargo = wti.CurrentToCargo,
                   CurrentCreateTime = wti.CurrentCreateTime,
                   CurrentUpdateTime = wti.CurrentUpdateTime
               })
               .FirstAsync();

            if (wCSWorkTaskInfoDto != null)
            {
                int sum = await _WorkTaskInfoRepository.AsSugarClient().Updateable<WorkTaskInfo>()
                   .SetColumns(it => new WorkTaskInfo()
                   {
                       TaskProcessState = EnumTaskProcessState.ErrorEmptyLoad,
                       UpdateTime = DateTime.Now
                   })
                   .Where(it => it.ID == wCSWorkTaskInfoDto.ID).ExecuteCommandAsync();
            }

            return wCSWorkTaskInfoDto;
        }

        public async Task<ScWorkModelInfo> ScGetScWorkModelInfoAsync(string scCode)
        {
            var scWorkModelInfo = await _WorkTaskInfoRepository.AsSugarClient()
           .Queryable<ScWorkModelInfo>().FirstAsync(it => it.ScEquipmentCode == scCode && it.IsLock == false);
            if (scWorkModelInfo == null)
            {
                throw new Exception($"{scCode}没有配置工作模式数据");
            }
            return scWorkModelInfo;
        }

        public async Task ScUpdateScWorkModelInfoAsync(ScWorkModelInfo scWorkModelInfo)
        {
            await _WorkTaskInfoRepository.AsSugarClient().Updateable<ScWorkModelInfo>(scWorkModelInfo).ExecuteCommandAsync();
        }

        public async Task<PlcWriteDbInfo> ScGetPlcWriteDbInfoAsync(string scEquipment, string objectType)
        {
            var plcwritedb = await _WorkTaskInfoRepository.AsSugarClient().Queryable<PlcWriteDbInfo>().FirstAsync(it => it.EquipmentCode == scEquipment && it.ObjectType == objectType);
            if (plcwritedb == null)
            {
                throw new Exception($"设备编号{scEquipment}和类型{objectType}不存在配置的DB数据");
            }
            return plcwritedb;
        }

        public async Task<bool> ScUpdateWorkTaskInfoAsync(WCSWorkTaskInfoDto wCSWorkTaskInfoDto)
        {
            int sum = await _WorkTaskInfoRepository.AsSugarClient().Updateable<WorkTaskInfo>()
                       .SetColumns(it => new WorkTaskInfo()
                       {
                           TaskProcessState = wCSWorkTaskInfoDto.TaskProcessState,
                           TaskState = wCSWorkTaskInfoDto.TaskState,
                           UpdateTime = wCSWorkTaskInfoDto.UpdateTime,
                           CurrentDetailTaskState = wCSWorkTaskInfoDto.CurrentDetailTaskState,
                           CurrentUpdateTime = wCSWorkTaskInfoDto.CurrentUpdateTime,
                           UploadWmsState = wCSWorkTaskInfoDto.UploadWmsState,
                           UploadWmsTime = wCSWorkTaskInfoDto.UploadWmsTime
                       })
                       .Where(it => it.ID == wCSWorkTaskInfoDto.ID).ExecuteCommandAsync();
            return sum > 0 ? true : false;
        }

        public async Task<bool> ScUpdateWorkTaskInfoRouteDetailAsync(WCSWorkTaskInfoDto wCSWorkTaskInfoDto)
        {
            int sum = await _WorkTaskInfoRepository.AsSugarClient().Updateable<WorkTaskInfo>()
                     .SetColumns(it => new WorkTaskInfo()
                     {
                         TaskProcessState = wCSWorkTaskInfoDto.TaskProcessState,
                         CurrentRounteDetailID = wCSWorkTaskInfoDto.CurrentRounteDetailID,
                         CurrentDetailTaskState = wCSWorkTaskInfoDto.CurrentDetailTaskState,
                         CurrentDispatchType = wCSWorkTaskInfoDto.CurrentDispatchType,
                         CurrentFromEquipment = wCSWorkTaskInfoDto.CurrentFromEquipment,
                         CurrentFromCargo = wCSWorkTaskInfoDto.CurrentFromCargo,
                         CurrentToEquipment = wCSWorkTaskInfoDto.CurrentToEquipment,
                         CurrentToCargo = wCSWorkTaskInfoDto.CurrentToCargo,
                         CurrentCreateTime = wCSWorkTaskInfoDto.CurrentCreateTime,
                         CurrentUpdateTime = wCSWorkTaskInfoDto.CurrentUpdateTime,
                     })
                     .Where(it => it.ID == wCSWorkTaskInfoDto.ID).ExecuteCommandAsync();
            return sum > 0 ? true : false;
        }

        public async Task<WCSWorkTaskInfoDto> ScGetWorkTaskInfoByWcsTaskCodeAsync(int wcstaskcode)
        {
            var exp = Expressionable.Create<WorkTaskInfo, RouteDetailInfo>();
            exp.AndIF(true, (wti, ri) => wti.TaskCode == wcstaskcode);
            exp.AndIF(true, (wti, ri) => wti.TaskState == EnumTaskState.Executing);
            exp.AndIF(true, (wti, ri) => wti.CurrentDetailTaskState == EnumDetailTaskState.Executing);


            var wCSWorkTaskInfoDto = await _WorkTaskInfoRepository.AsSugarClient()
               .Queryable<WorkTaskInfo, RouteDetailInfo>((wti, ri) => new JoinQueryInfos(JoinType.Inner, wti.CurrentRounteDetailID == ri.ID))
               .Where(exp.ToExpression())
               .OrderBy((wti, ri) => wti.SaveTime, OrderByType.Desc)
               .Select((wti, ri) => new WCSWorkTaskInfoDto()
               {
                   ID = wti.ID,
                   RouteID = wti.RouteID,
                   Priority = wti.Priority,
                   PalletCode = wti.PalletCode,
                   TaskCode = wti.TaskCode,
                   TaskProcessState = wti.TaskProcessState,
                   TaskState = wti.TaskState,
                   TaskType = wti.TaskType,
                   SaveTime = wti.SaveTime,
                   UpdateTime = wti.UpdateTime,
                   WmsTaskCode = wti.WmsTaskCode,
                   DependWmsTaskCode = wti.DependWmsTaskCode,
                   WmsFromStation = wti.WmsFromStation,
                   WmsFromPosition = wti.WmsFromPosition.ToString(),
                   WmsToStation = wti.WmsToStation,
                   WmsToPosition = wti.WmsToPosition,
                   CurrentRounteDetailID = wti.CurrentRounteDetailID,
                   CurrentDetailTaskState = wti.CurrentDetailTaskState,
                   CurrentDispatchType = wti.CurrentDispatchType,
                   CurrentFromEquipment = wti.CurrentFromEquipment,
                   CurrentFromCargo = wti.CurrentFromCargo,
                   CurrentToEquipment = wti.CurrentToEquipment,
                   CurrentToCargo = wti.CurrentToCargo,
                   CurrentCreateTime = wti.CurrentCreateTime,
                   CurrentUpdateTime = wti.CurrentUpdateTime
               })
               .FirstAsync();

            return wCSWorkTaskInfoDto;
        }

        public async Task<RouteDetailInfo> GetRouteDetailInfoByIdAsync(long Id)
        {
            var routeDetailInfo = await _WorkTaskInfoRepository.AsSugarClient()
                 .Queryable<RouteDetailInfo>().FirstAsync(it => it.ID == Id);
            if (routeDetailInfo == null)
            {
                throw new Exception($"路径详细ID: {Id}没有配置数据");
            }
            return routeDetailInfo;
        }

        public async Task<RouteDetailInfo> GetNextRouteDetailInfoByIdAsync(long Id)
        {
            var routeDetailInfo = await _WorkTaskInfoRepository.AsSugarClient()
              .Queryable<RouteDetailInfo>().FirstAsync(it => it.PrevionsID == Id);
            if (routeDetailInfo == null)
            {
                throw new Exception($"路径详细前一段ID: {Id}没有配置数据");
            }
            return routeDetailInfo;
        }

        public async Task<bool> InsertTaskRouteDetailRecordInfoAsync(TaskRouteDetailRecordInfo taskRouteDetailRecordInfo)
        {
            taskRouteDetailRecordInfo.ID = _Sonoflake.GetId();
            var sum = await _WorkTaskInfoRepository.AsSugarClient().Insertable(taskRouteDetailRecordInfo).ExecuteCommandAsync();
            return sum > 0 ? true : false;
        }

        public async Task<bool> WcsUpdateReallotLocationAsync(WCSWorkTaskInfoDto wCSWorkTaskInfoDto)
        {
            int sum = await _WorkTaskInfoRepository.AsSugarClient().Updateable<WorkTaskInfo>()
              .SetColumns(it => new WorkTaskInfo()
              {
                  TaskProcessState = wCSWorkTaskInfoDto.TaskProcessState,
                  WmsToPosition = wCSWorkTaskInfoDto.WmsToPosition,
                  UpdateTime = wCSWorkTaskInfoDto.UpdateTime,
                  CurrentToCargo = wCSWorkTaskInfoDto.CurrentToCargo,
                  CurrentUpdateTime = wCSWorkTaskInfoDto.CurrentUpdateTime
              })
              .Where(it => it.ID == wCSWorkTaskInfoDto.ID).ExecuteCommandAsync();
            return sum > 0 ? true : false;
        }

        public async Task<bool> WcsUpdateTakeEmptyAsync(WCSWorkTaskInfoDto wCSWorkTaskInfoDto)
        {
            int sum = await _WorkTaskInfoRepository.AsSugarClient().Updateable<WorkTaskInfo>()
           .SetColumns(it => new WorkTaskInfo()
           {
               TaskState = wCSWorkTaskInfoDto.TaskState,
               UpdateTime = wCSWorkTaskInfoDto.UpdateTime,
           })
           .Where(it => it.ID == wCSWorkTaskInfoDto.ID).ExecuteCommandAsync();
            return sum > 0 ? true : false;
        }

        /// <summary>
        /// 通过Sc设备异步获得真实地段的位置
        /// </summary>
        /// <param name="scequipment"></param>
        /// <returns></returns>
        public async Task<WCSWorkTaskInfoDto> ScGetReallotLocationByScEquipmentAsync(string scequipment)
        {
            var exp = Expressionable.Create<WorkTaskInfo, RouteDetailInfo>();
            exp.AndIF(true, (wti, ri) => wti.CurrentToEquipment == scequipment);
            exp.AndIF(true, (wti, ri) => wti.TaskState == EnumTaskState.Executing);
            exp.AndIF(true, (wti, ri) => wti.CurrentDetailTaskState == EnumDetailTaskState.Executing);
            exp.AndIF(true, (wti, ri) => wti.TaskProcessState == EnumTaskProcessState.ReAllotLocation);

            var wCSWorkTaskInfoDto = await _WorkTaskInfoRepository.AsSugarClient()
               .Queryable<WorkTaskInfo, RouteDetailInfo>((wti, ri) => new JoinQueryInfos(JoinType.Inner, wti.CurrentRounteDetailID == ri.ID))
               .Where(exp.ToExpression())
               .Select((wti, ri) => new WCSWorkTaskInfoDto()
               {
                   ID = wti.ID,
                   RouteID = wti.RouteID,
                   Priority = wti.Priority,
                   PalletCode = wti.PalletCode,
                   TaskCode = wti.TaskCode,
                   TaskProcessState = wti.TaskProcessState,
                   TaskState = wti.TaskState,
                   TaskType = wti.TaskType,
                   SaveTime = wti.SaveTime,
                   UpdateTime = wti.UpdateTime,
                   WmsTaskCode = wti.WmsTaskCode,
                   DependWmsTaskCode = wti.DependWmsTaskCode,
                   WmsFromStation = wti.WmsFromStation,
                   WmsFromPosition = wti.WmsFromPosition.ToString(),
                   WmsToStation = wti.WmsToStation,
                   WmsToPosition = wti.WmsToPosition,
                   CurrentRounteDetailID = wti.CurrentRounteDetailID,
                   CurrentDetailTaskState = wti.CurrentDetailTaskState,
                   CurrentDispatchType = wti.CurrentDispatchType,
                   CurrentFromEquipment = wti.CurrentFromEquipment,
                   CurrentFromCargo = wti.CurrentFromCargo,
                   CurrentToEquipment = wti.CurrentToEquipment,
                   CurrentToCargo = wti.CurrentToCargo,
                   CurrentCreateTime = wti.CurrentCreateTime,
                   CurrentUpdateTime = wti.CurrentUpdateTime
               })
               .FirstAsync();

            return wCSWorkTaskInfoDto;
        }

        public async Task<int> WCSCheckSCHaveExcuecutingTaskWork(string scCode)
        {
            var wcscount = await _WorkTaskInfoRepository.AsSugarClient()
             .Queryable<WorkTaskInfo>().CountAsync(it => it.TaskState == EnumTaskState.Executing &&
             it.CurrentDetailTaskState == EnumDetailTaskState.Executing &&
             (it.CurrentFromEquipment == scCode || it.CurrentToEquipment == scCode));
            return wcscount;
        }


        /// <summary>
        /// 入库结束任务
        /// </summary>
        /// <param name="scCode"></param>
        /// <returns></returns>
        public async Task<WMSApiDomain.WebApi.HeaderResult<bool>> WCSInEndTaskWork(long wmsTaskCode, string container, string equipment)
        {
            return await WCSMessageWithWMSApi.WCSNoticeTaskAutoCompleteAsync(wmsTaskCode, container, equipment);
        }
        /// <summary>
        /// 入库结束任务
        /// </summary>
        /// <param name="scCode"></param>
        /// <returns></returns>
        public async Task<bool> WCSInEndTaskWork(long wmsTaskCode)
        {
            return await WCSMessageWithWMSApi.WCSNoticeTaskAutoCompleteAsync(wmsTaskCode);
        }

        /// <summary>
        /// 出库释放货位
        /// </summary>
        /// <param name="scCode"></param>
        /// <returns></returns>
        public async Task<WMSApiDomain.WebApi.HeaderResult<bool>> WCSOutTaskWork(long wmsTaskCode)
        {
            return await WCSMessageWithWMSApi.WCSNoticePalltetArriveDoEquipmentAsync(wmsTaskCode);
        }




        /// <summary>
        /// WMS手动解绑通知WCS手动完成任务
        /// </summary>
        /// <param name="unbandinWCS"></param>
        /// <returns></returns>
        public async Task<Zocono.Infrastructure.Common.HeaderResult<bool>> WMSManualUnbindingNotificationAsync(UnbandinWCS unbandinWCS)
        {
            RunLogInfo runLogInfo = new RunLogInfo();
            runLogInfo.RunType = "WMS手动解绑通知WCS手动完成任务";//业务类型
            runLogInfo.ContainerBarcode = unbandinWCS.ContainerCode;//解绑的托盘码

            Zocono.Infrastructure.Common.HeaderResult<bool> result = new();
            try
            {
                var exp = Expressionable.Create<WorkTaskInfo>();
                exp.AndIF(true, wi => wi.PalletCode == unbandinWCS.ContainerCode && (wi.TaskState == EnumTaskState.Executing || wi.TaskState == EnumTaskState.Initial));

                var task = await _WorkTaskInfoRepository.AsSugarClient().Queryable<WorkTaskInfo>().Where(exp.ToExpression()).OrderBy(it => it.CurrentUpdateTime, OrderByType.Desc).FirstAsync();

                if (task != null)
                {
                    task.TaskState = EnumTaskState.ManualFinish;
                    task.CurrentDetailTaskState = EnumDetailTaskState.Finish;
                    task.TaskProcessState = EnumTaskProcessState.ScUnloaded;
                    task.CurrentUpdateTime = DateTime.Now;

                    await _WorkTaskInfoRepository.UpdateAsync(task);

                    runLogInfo.RunLog = $"WMS手动解绑，WCS手动完成任务成功";
                    //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);

                    result.IsSucceed = true;
                    result.Message = "成功";
                }
                else
                {
                    var expl = Expressionable.Create<WorkTaskInfo>();
                    expl.AndIF(true, wi => wi.PalletCode == unbandinWCS.ContainerCode && (wi.TaskState == EnumTaskState.Finish || wi.TaskState == EnumTaskState.ManualFinish));

                    var worktask = await _WorkTaskInfoRepository.AsSugarClient().Queryable<WorkTaskInfo>().Where(expl.ToExpression()).OrderBy(wi => wi.CurrentUpdateTime, OrderByType.Desc).FirstAsync();

                    if (worktask != null)
                    {
                        runLogInfo.RunLog = $"WMS手动解绑，WCS手动完成任务失败，WCS任务状态是完成";

                        result.IsSucceed = false;
                        result.Message = "WMS手动解绑，WCS手动完成任务失败，WCS任务状态是完成";
                    }
                    else
                    {
                        runLogInfo.RunLog = $"WMS手动解绑，WCS手动完成任务失败，WCS任务列表不存在该任务";

                        result.IsSucceed = false;
                        result.Message = "WMS手动解绑，WCS手动完成任务失败，WCS任务列表不存在该任务";
                    }

                }
            }
            catch (Exception e)
            {
                runLogInfo.RunLog = $"WMS手动解绑，WCS手动完成任务失败，WMSManualUnbindingNotificationAsync执行错误";

                result.IsSucceed = false;
                result.Message = e.Message;
            }
            await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
            return result;

        }

        /// <summary>
        /// 根据设备号获取plc读DB配置
        /// </summary>
        /// <param name="scEquipment"></param>
        /// <param name="objectType"></param>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<PlcReadDbInfo> PlannerGetPlcReadDbInfoAsync(string scEquipment, string objectType)
        {
            var plcreaddb = await _WorkTaskInfoRepository.AsSugarClient().Queryable<PlcReadDbInfo>().FirstAsync(it => it.EquipmentCode == scEquipment && it.ProcessModuleName == objectType);
            if (plcreaddb == null)
            {
                throw new Exception($"设备编号{scEquipment}和类型{objectType}不存在配置的DB数据");
            }
            return plcreaddb;
        }
    }
}
